gpt4 book ai didi

typescript - 在 Typescript 中,什么是 !取消引用成员时的(感叹号/爆炸)运算符?

转载 作者:太空狗 更新时间:2023-10-29 19:34:36 25 4
gpt4 key购买 nike

在查看 tslint 规则的源代码时,我遇到了以下语句:

if (node.parent!.kind === ts.SyntaxKind.ObjectLiteralExpression) {
return;
}

请注意 node.parent 之后的 ! 运算符。有趣!

我首先尝试使用我当前安装的 TS (1.5.3) 版本在本地编译文件。由此产生的错误指向爆炸的确切位置:

$ tsc --noImplicitAny memberAccessRule.ts 
noPublicModifierRule.ts(57,24): error TS1005: ')' expected.

接下来我升级到最新的 TS (2.1.6),编译它没有问题。所以它似乎是 TS 2.x 的特性。 但是 转译完全忽略了爆炸,导致以下 JS:

if (node.parent.kind === ts.SyntaxKind.ObjectLiteralExpression) {
return;
}

到目前为止,我的 Google fu 让我失望了。

什么是 TS 的感叹号运算符,它是如何工作的?

最佳答案

那是非空断言运算符。这是一种告诉编译器“这个表达式不能是 nullundefined 的方法,所以不要提示它可能是 nullundefined 。”有时类型检查器无法自行做出决定。

the TypeScript release notes 中有解释:

A new ! post-fix expression operator may be used to assert that its operand is non-null and non-undefined in contexts where the type checker is unable to conclude that fact. Specifically, the operation x! produces a value of the type of x with null and undefined excluded. Similar to type assertions of the forms <T>x and x as T, the ! non-null assertion operator is simply removed in the emitted JavaScript code.

我发现在该解释中使用术语“断言”有点误导。它是“断言”的意思是开发人员正在断言,而不是要执行测试的意思。最后一行确实表明它不会导致发出任何 JavaScript 代码。

关于typescript - 在 Typescript 中,什么是 !取消引用成员时的(感叹号/爆炸)运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43648775/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com