繁体   English   中英

TypeScript:关于可选链的困惑

[英]TypeScript: Confusion about optional chaining

我有这个代码片段。

interface OBJ {
  a: {
    b?: {
      c?: number;
    };
  };
}

const obj: OBJ = {
  a: {
    b: {
      c: 1
    }
  }
};

if (obj.a.b.c === 1) {
  console.log("here");
}

首先,TS 编译器抱怨Object is possibly 'undefined'.ts(2532) at obj 我不明白,因为在我看来对象确实已定义,只是根据接口bc属性可以未定义。

然后我想我可以在它上面使用可选链接

if (obj.a.b?.c === 1) {
  console.log("here");
}

但是这次编译器说有语法错误

/src/index.ts: Unexpected token (9:14)

   7 |     }   
   8 | };
>  9 | if (obj.a.b ? .c === 1 : ) {
     |              ^   
  10 |     console.log("here");
  11 | }
  12 | //#

我在这里缺少什么? 有人可以向我解释这两个问题吗?

现场演示: https : //codesandbox.io/s/wizardly-booth-idpy5?file=/ src/ index.ts

首先,TS 编译器抱怨 Object 可能是 'undefined'.ts(2532) at obj。 我不明白,因为在我看来对象确实已定义,只是根据接口 b 和 c 属性可以未定义。

是的,编译器显示b可以是未定义的。 此消息与a无关。 您可以通过更改if (obj.a === 1) - 现在没有错误来轻松检查这一点。

构造if (obj.ab?.c === 1)将被转换为if (((_a = obj.ab) === null || _a === void 0 ? void 0 : _a.c) === 1)编译后。 我更喜欢使用旧的好守卫:

if (obj.a.b && obj.a.b.c === 1) {
  console.log("here");
}

但是这次编译器说有语法错误

这很奇怪。 从 TS 3.7 开始,这应该不是错误。 查看另一个在线沙箱: 单击 你会看到这里没有错误。

扩展@Anton的答案

您在示例中使用了包裹打包器。 您需要告诉parcel 使用哪个版本的打字稿(支持可选链运算符的版本),错误就会消失。

包.json:

"devDependencies": {
    "parcel-bundler": "^1.6.1",
    "typescript": "^4.0.2"
},

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM