I tried to get the value in the object using typescript using ? operator. But it's throwing an error.
const data = {sample:{sample1:''hai'}}
! operator used its working fine
Success Case
if(data.sample!['sample1']){
console.log('hai')
}
?. Operator used its throwing error
Error Case
if(data.sample?.['sample1']){
console.log('hai')
}
How to get the value using ?. operator
The
?.operator (aka optional chaining operator, aka optional property access operator, aka Elvis operator) was only introduced in TypeScript 3.7.In TypeScript 3.7+, the following code compiles and executes without a problem:
Since you tagged your question with typescript-3.6, you'll either have to upgrade your version of TypeScript, or revert to more explicit checking for values that are
nullorundefined.