首页 > 解决方案 > TypeScript:关于可选链接的困惑

问题描述

我有这个代码片段。

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。我不明白,因为在我看来对象确实已定义,只是根据接口,bandc属性可以未定义。

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

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

标签: javascripttypescript

解决方案


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

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

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

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

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

这很奇怪。由于 TS 3.7 这不应该是一个错误。查看另一个在线沙盒:单击。你会看到这里没有错误。


推荐阅读