optional chaining

There's a handy syntactic sugar introduced in Typescript 3.7 called optional chaining.

# without optional chaining  
const baz = foo && foo.bar  && foo.bar.baz  
  
# with optional chaining  
const baz = for?.bar?.baz  

The ?. operator functions similarly to the . chaining operator, except that instead of causing an error if a reference is nullish (null or undefined), the expression short-circuits with a return value of undefined.

MDN Web docs

It works also for arrays.


Would you like to connect? Subscribe via email or RSS , or follow me on Twitter!