版本 <3.7 的打字稿文件是否有安全导航运算符的替代方案

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

我一直在寻找安全导航运算符的替代品,因为我的打字稿版本是 3.2。 如果我必须检查 3 到 4 个键,我的代码会变得非常冗长。

假设我想检查 Obj.key1.key2,key3 那么我的代码是这样的

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

我制作了这个函数,它可以用作打字稿版本 <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);
    }
  }
}

此功能在 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 中称为“可选链接”。

如所描述的那样,并在其问题 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 or Babel's env for ES2020 中进行了讨论。因此,对于大多数开发人员来说,采用现代版本的 TypeScript 工具比使用替代实现更有意义。

如果您确实无法使用现代工具,则需要一个辅助方法;作为一种语言特性,可选链接不能直接被填充。许多通用库中存在经过兼容测试的替代品: