Search code examples
javascripttypescriptoptional-chaining

?. in Typescript?


Is ?. a valid operator in Typescript or Javascript?

I have seen code like below:

const var1 = obj1?.innerObj1?.somePropVal; 

When I try this in the chrome console, I get an error if obj1 is undefined. Not sure whether this kind of code would work.

Let me know if I am missing something.


Solution

  • const var1 = obj1?.innerObj1?.somePropVal;
    

    is the same as:

    const var1 = obj1 && obj1.innerObj1 ? obj1.innerObj1.somePropVal : undefined;