user38643
user38643

Reputation: 469

Check is key is present and true on key within an optional object?

I have an object in this interface:

export interface CoolThing {
    thisOptionalField?: {}
}

I want to check if thisOptionalField has a key on it myCoolKey set to true.

Attempt

  if (!!ctx.CoolThing?.thisOptionalField && !!ctx.CoolThing?.CoolThing["thisOptionalField"] == true) {
    ....
  }

How can I achieve this?

I'm also looking at [key: string]: unknown

Upvotes: 0

Views: 507

Answers (1)

Ivaylo Valchev
Ivaylo Valchev

Reputation: 10415

To check if an object contains a field in JS or TS can be done in a few ways. The easiest way is to do:

if (ctx.CoolThing) {
   // has the 'thisOptionalField' field
   if ('thisOptionalField' in ctx.Coolthing) {
      // it is set to true
      if (ctx.Coolthing['thisOptionalField'] === true) {
          // do something
      }
   }
}

In TS, I'd recommend you either have [key: string]: unknown, or better yet Record<string, unknown> instead of an anonymous object like that.

Upvotes: 1

Related Questions