javascript - 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
。我不明白,因为在我看来对象确实已定义,只是根据接口,b
andc
属性可以未定义。
然后我想我可以在上面使用可选链接
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 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");
}
但是这次编译器说有语法错误
推荐阅读
- azure - ASP.NET Core Web 应用程序的 Azure AD 身份验证
- amazon-web-services - Dokku:Nginx 失败,地址已在使用中
- coldfusion - ColdFusion 11 编译 CFC 花费了太多时间
- android - 离线时带有 AppCenter 的 Xamarin.Forms 应用程序崩溃 (android.content.ContextWrapper.getSystemService)
- javascript - CircleCi 偶尔无法在构建中连接到 Postgres
- javascript - Reveal Elemen on Touch / Click exept on Link Href
- sql - “无法将值 NULL 插入列”插入语句中的 PK 和 FK 错误
- python - 从数据框单元格中的字符串中删除单词/字符?
- sql-server - 为什么将列从 nvarchar 更改为 varchar 会导致 mdf 文件大幅增长?
- ruby-on-rails - 启动 puma w/o `bundle exec` 工作;不适用于捆绑执行;BUNDLE_APP_CONFIG env var 在 RUBYOPT="-rbundler/setup" 运行期间不可用