安全导航运算符 (?.) 或 (!.) 和空属性路径 [英] Safe navigation operator (?.) or (!.) and null property paths
问题描述
在 Angular 2 模板中,安全运算符 ?.
有效,但在使用 TypeScript 2.0 的 component.ts
中无效.此外,安全导航操作符 (!.
) 不起作用.
In Angular 2 templates safe operator ?.
works, but not in component.ts
using TypeScript 2.0. Also, safe navigation operator (!.
) doesn't work.
例如:
这个打字稿
if (a!.b!.c) { }
编译成这个 JavaScript
compiles to this JavaScript
if (a.b.c) { }
但是当我运行它时,出现以下错误:
But when I run it, I get the follow error:
无法读取未定义的属性b"
Cannot read property 'b' of undefined
以下有什么替代方法吗?
Is there any alternative to the following?
if (a && a.b && a.b.c) { }
推荐答案
自从 TypeScript 3.7 发布后,您现在可以使用可选链了.
Since TypeScript 3.7 was released you can use optional chaining now.
属性示例:
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
otherFn
will be called only if otherFn
won't be equal to null
or undefined
在 IF 语句中使用可选链
这个:
if (someObj && someObj.someProperty) {
// ...
}
现在可以用这个替换
if (someObj?.someProperty) {
// ...
}
参考:https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html
这篇关于安全导航运算符 (?.) 或 (!.) 和空属性路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!