![](/img/trans.png)
[英]confusion about chaining $q promises with angular and 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
。 我不明白,因為在我看來對象確實已定義,只是根據接口b
和c
屬性可以未定義。
然后我想我可以在它上面使用可選鏈接
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");
}
但是這次編譯器說有語法錯誤
擴展@Anton的答案
您在示例中使用了包裹打包器。 您需要告訴parcel 使用哪個版本的打字稿(支持可選鏈運算符的版本),錯誤就會消失。
包.json:
"devDependencies": {
"parcel-bundler": "^1.6.1",
"typescript": "^4.0.2"
},
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.