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

标签 typescript tslint

在查看 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/44871788/

相关文章:

javascript - Angular 登录表单验证

typescript - 如何使用带有更新的 FirestoreDataConverter?

angular - tslint/codelyzer/ng lint 错误 : "for (... in ...) statements must be filtered with an if statement"

angular - 异步管道不应被否定

typescript - tslint 中的 "no-string-literal"规则是什么?

typescript - Angular2中注入(inject)服务属性的变化检测

Angular 6 - ForkJoin 没有导出成员

typescript - 当看似相同的三元运算符构造没有时,为什么使用 'if-else' 语句会产生 TypeScript 编译器错误?

visual-studio-code - VSCode 仅针对打开的文件显示 TSLint 错误

angular - 如何在 Angular 中定义枚举类型以不违反 tslint typedef 规则