Reputation: 469
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
.
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
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