问题描述
自 TypeScript 3.7 发布以来,您现在可以使用可选链。
let x = foo?.bar.baz();
这相当于:
let x = (foo === null || foo === undefined)
? undefined
: foo.bar.baz();
此外,您可以致电:
function(otherFn: (par: string) => void) {
otherFn?.("some value");
}
otherFn``otherFn
仅当不等于null
或时才会调用undefined
这个:
if (someObj && someObj.someProperty) {
// ...
}
现在可以用这个替换
if (someObj?.someProperty) {
// ...
}
参考:https ://www.typescriptlang.org/docs/handbook/release- notes/typescript-3-7.html
解决方法
在 Angular 2 模板中,安全运算符?.
有效,但在component.ts
使用 TypeScript 2.0 时无效。此外,安全导航运算符 (!.
) 不起作用。
例如:
这个打字稿
if (a!.b!.c) { }
编译为此 JavaScript
if (a.b.c) { }
但是当我运行它时,我收到以下错误:
无法读取未定义的属性“b”
是否有以下替代方案?
if (a && a.b && a.b.c) { }