cuốn sách gpt4 ai đã làm

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

In lại Tác giả: Walker 123 更新时间:2023-11-28 03:18:49 46 4
mua khóa gpt4 Nike

在查看 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的感叹号运算符是什么,它是如何工作的?

câu trả lời hay nhất

这是非空断言运算符。这是一种告诉编译器“这里的表达式不能是 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ịkhông xác định excluded. Similar to type assertions of the forms xx as T, the ! non-null assertion operator is simply removed in the emitted JavaScript code.

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

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

46 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress