I would like to use optional chaining operator in typescript, but I get the error Property 'dog' does not exist on type '{ name: string; cat: Record<string, string>; }'.
. Totally make sense the error complain from typescript but I am wondering if anyway for me to walk around?
playground
const adventurer: {name: string;cat:Record<string, string>} = {
name: 'Alice',
cat: {
name: 'Dinah'
}
};
const dogName = adventurer?.dog;
console.log(dogName);
You are telling the TS compiler by providing a type for adventurer, that adventurer will never have a property dog (EDIT: thanks @jcalz for pointing out that's not exactly true. Have a look at the comment below for more info). There are two main ways around this:
const dogName = (adventurer as any)?.dog;
console.log(dogName);
dogconst adventurer: {name: string;cat:Record<string, string>; dog?: string} = {
name: 'Alice',
cat: {
name: 'Dinah'
}
};
const dogName = adventurer?.dog;
console.log(dogName);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With