Search code examples
angulartypescriptsafe-navigation-operator

Is there any Alternate of Safe Navigation Operator for typescript file for versions <3.7


I was Looking for alternate of safe navigation operator as my typescript version is 3.2. My code becomes very much lengthy if I have to check for 3 to 4 keys.

Suppose I want to check for Obj.key1.key2,key3 then my code goes like this

if((Obj != undefined || Obj!= null)&&
   (Obj.key1 != undefined || Obj.key!= null)&&
   (Obj.key1.key2 != undefined || Obj.key1.key2!= null)&&
   (Obj.key1.key2.key3 != undefined || Obj.key1.key2.key3!= null)&&
   Obj.key1.key2.key3 == some_value){
    //do something...
}

Solution

  • This feature, called "optional chaining" in MDN and other ECMAScript documentation, was moved to Stage 4 (ready for inclusion) in December 2019 and is published as part of ES2020. As of October 2021, according to caniuse.com, browser support is currently at 90.86% globally.

    As described, and as discussed in its issue Microsoft/TypeScript#16, Typescript support for optional chaining was released on 5 November 2019—nearly two years ago at the time of this answer. Compilation solutions also exist in Webpack 5 or Babel's env for ES2020. As such, for most developers, it makes more sense to adopt modern versions of TypeScript tooling than to use an alternative implementation.

    If you are strictly unable to use modern tooling, you'll need a helper method; as a language feature, optional chaining cannot be directly polyfilled. Compatible tested alternatives exist in a number of common libraries: