#How to idiomatically select object property or true if undefined?

6 messages · Page 1 of 1 (latest)

rough kayak
#

I'm not idiomatic at all in JS and have a situation where I want to extract an object's boolean property. If it's there, I use it. If it's not, I default to true. My unseasoned JS/TS mind did this:

const anObjectProperty: boolean = myObject?.myProperty ? myObject.myProperty : true

I suspect TS devs may have some idiomatic way like all the ?? and other things I don't know atm 😆
Thank you for your time 🙂

rough kayak
#

Actually seems like a good way is indeed
const anObjectProperty = myObject?.myProperty ?? true

#

!resolve

neon geode
dreamy sedgeBOT
#
mishall8399#0

Preview:```ts
const myObject = {
myProperty: false,
}

console.log(
myObject?.myProperty ? myObject.myProperty : true
)
console.log(myObject?.myProperty || true)
console.log(myObject?.myProperty ?? true)```

rough kayak
#

Thank you very much Aswin :) was unaware of ||