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

Time:10-05

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...
}

CodePudding user response:

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:

CodePudding user response:

I made this function which can be used as alternate of safe navigation operator for typescript versions <3.7

/*
  This function is to validate if Object is accessible or not as well as returns its value if it is accessible.
  it will return false if Object is not accessible (if value is null or undefined)
  If Object is accessible then it will return its value.

  Example: if I want to check that is "obj.key1.key2" is accessible and I want to put check on its value.
  if (isAccessible(obj,["key1","key2"]) == some_value){
    ...do something...
  }

  no need to check for null and undefined for each key.

  NOTE: this function is alternate of "SAFE NAVIGATOR OPERATOR (?)" of typescript which is not supported in versions <3.7
*/

isAccessible(data, keys, start=0) {
  if (start == 0 && (data == null || data == undefined)) {
    console.warn("data",data);
    return data;
  } else {
    if (data[keys[start]] == null || data[keys[start]] == undefined) {
      console.warn("Object valid till", keys.slice(0,start),keys[start],"undefined");
      return data[keys[start]];
    } else {
      if (start   1 >= keys.length) {
        // console.log("output",data[keys[start]]);
        return data[keys[start]];
      }
      return this.isAccessible(data[keys[start]], keys, start   1);
    }
  }
}
  • Related