简体   繁体   English

TypeScript:关于可选链的困惑

[英]TypeScript: Confusion about optional chaining

I have this code snippet.我有这个代码片段。

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

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

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

Firstly the TS compiler complains about Object is possibly 'undefined'.ts(2532) at obj .首先,TS 编译器抱怨Object is possibly 'undefined'.ts(2532) at obj I don't get it since it looks to me like the object is indeed defined, it is just according to the interface the b and c property can be undefined.我不明白,因为在我看来对象确实已定义,只是根据接口bc属性可以未定义。

then I thought I could use optional chaining on it然后我想我可以在它上面使用可选链接

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

However this time the compiler says there is a syntax error但是这次编译器说有语法错误

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

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

What am I missing here?我在这里缺少什么? Can someone please explain these two questions to me?有人可以向我解释这两个问题吗?

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

Firstly the TS compiler complains about Object is possibly 'undefined'.ts(2532) at obj.首先,TS 编译器抱怨 Object 可能是 'undefined'.ts(2532) at obj。 I don't get it since it looks to me like the object is indeed defined, it is just according to the interface the b and c property can be undefined.我不明白,因为在我看来对象确实已定义,只是根据接口 b 和 c 属性可以未定义。

Yes, compiler shows that b can be undefined.是的,编译器显示b可以是未定义的。 This message is not about the a .此消息与a无关。 You can easily check this by changing if (obj.a === 1) - no error now.您可以通过更改if (obj.a === 1) - 现在没有错误来轻松检查这一点。

The construction if (obj.ab?.c === 1) will be converted to if (((_a = obj.ab) === null || _a === void 0 ? void 0 : _a.c) === 1) after compile.构造if (obj.ab?.c === 1)将被转换为if (((_a = obj.ab) === null || _a === void 0 ? void 0 : _a.c) === 1)编译后。 I prefer using old good guards:我更喜欢使用旧的好守卫:

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

However this time the compiler says there is a syntax error但是这次编译器说有语法错误

This is strange.这很奇怪。 Since TS 3.7 this should not be an error.从 TS 3.7 开始,这应该不是错误。 Take a look on another online sandbox: click .查看另一个在线沙箱: 单击 You will see there is no error here.你会看到这里没有错误。

To extend the answer by @Anton扩展@Anton的答案

You are using parcel bundler in your sample.您在示例中使用了包裹打包器。 You need to tell parcel which version of typescript to use (the one that supports optional chaining operator) and the error will go away.您需要告诉parcel 使用哪个版本的打字稿(支持可选链运算符的版本),错误就会消失。

package.json:包.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