How to check key and values inside in object using typescript

64 Views Asked by At

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

1

There are 1 best solutions below

2
Robby Cornelissen On BEST ANSWER

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:

const data = { sample: { sample1: 'hai' } };
console.log(data.sample?.['sample1']); 

Since you tagged your question with , you'll either have to upgrade your version of TypeScript, or revert to more explicit checking for values that are null or undefined.