在查看 tslint 规则的源代码时,我发现了以下语句:
if (node.parent!.kind === ts.SyntaxKind.ObjectLiteralExpression) {
trở lại;
}
Để ý node.parent
之后的 !
运算符。有趣!
我首先尝试使用当前安装的 TS 版本 (1.5.3) 在本地编译该文件。由此产生的错误指向爆炸的确切位置:
$ tsc --noImplicitAny memberAccessRule.ts
noPublicModifierRule.ts(57,24): error TS1005: ')' expected.
接下来,我升级到最新的TS(2.1.6),编译没有问题。所以这似乎是 TS 2.x 的一个特性。 Nhưng,转译完全忽略了爆炸,导致以下 JS:
if (node.parent.kind === ts.SyntaxKind.ObjectLiteralExpression) {
trở lại;
}
迄今为止,我的 Google fu 都让我失望了。
TS的感叹号运算符是什么,它是如何工作的?
这是非空断言运算符。这是一种告诉编译器“这里的表达式不能是 vô giá trị
hoặc không xác định
的方法,所以不要提示它可能是 vô giá trị
hoặc không xác định
”。有时类型检查器无法自行做出决定。
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 vô giá trị
Và không xác định
excluded. Similar to type assertions of the forms x
Và x as T
, the !
non-null assertion operator is simply removed in the emitted JavaScript code.
我发现在该解释中使用术语“断言”有点误导。它的“断言”是指开发人员正在断言,而不是指将要执行测试。最后一行确实表明它不会发出任何 JavaScript 代码。
Tôi là một lập trình viên xuất sắc, rất giỏi!