Mik*_*ain 338 typescript tslint
在查看tslint规则的源代码时,我遇到了以下语句:
if (node.parent!.kind === ts.SyntaxKind.ObjectLiteralExpression) {
return;
}
Run Code Online (Sandbox Code Playgroud)
注意!操作员之后node.parent.有趣!
我首先尝试使用我当前安装的TS版本(1.5.3)在本地编译该文件.结果错误指向爆炸的确切位置:
$ tsc --noImplicitAny memberAccessRule.ts
noPublicModifierRule.ts(57,24): error TS1005: ')' expected.
Run Code Online (Sandbox Code Playgroud)
接下来我升级到最新的TS(2.1.6),编译它没有问题.所以它似乎是TS 2.x的特征.但是,转化完全忽略了爆炸,导致以下JS:
if (node.parent.kind === ts.SyntaxKind.ObjectLiteralExpression) {
return;
}
Run Code Online (Sandbox Code Playgroud)
我的Google fu到目前为止都没有让我失望.
什么是TS的感叹号操作符,它是如何工作的?
Lou*_*uis 516
那是非空断言运算符.这是一种告诉编译器"这个表达式不能null或undefined在这里,所以不要抱怨它的可能性null或者undefined."的方法.有时类型检查器本身无法做出决定.
这里解释如下:
可以使用新的
!post-fix表达式运算符来断言其操作数在类型检查器无法推断该事实的上下文中是非空且非未定义的.具体而言,该操作x!产生x具有null和undefined排除的类型的值.类似键入的形式断言<T>x和x as T,所述!非空断言操作者简单地在所发射的JavaScript代码移除.
我发现在这个解释中使用"断言"一词有点误导.它是"断言"的,即开发人员断言它,而不是在将要执行测试的意义上.最后一行确实表明它不会发出任何JavaScript代码.
Mik*_*ain 115
路易斯的答案很棒,但我想我会试着简洁地总结一下:
bang运算符告诉编译器暂时放松它可能需要的"非空"约束.它告诉编译器:"作为开发人员,我比你更了解这个变量现在不能为null".
Mas*_*iri 42
非空断言运算符 (!) 帮助编译器确定该变量不是空变量或未定义变量。
let obj: { field: SampleType } | null | undefined;
... // some code
// the type of sampleVar is SampleType
let sampleVar = obj!.field; // we tell compiler we are sure obj is not null & not undefined so the type of sampleVar is SampleType
Run Code Online (Sandbox Code Playgroud)
Wil*_*een 25
使用非空断言运算符,我们可以明确地告诉编译器一个表达式的值不是nullorundefined。当编译器无法确定地推断类型但我们比编译器提供更多信息时,这会很有用。
TS代码
function simpleExample(nullableArg: number | undefined | null) {
const normal: number = nullableArg;
// Compile err:
// Type 'number | null | undefined' is not assignable to type 'number'.
// Type 'undefined' is not assignable to type 'number'.(2322)
const operatorApplied: number = nullableArg!;
// compiles fine because we tell compiler that null | undefined are excluded
}
Run Code Online (Sandbox Code Playgroud)
编译的JS代码
请注意,JS 不知道 Non-null 断言运算符的概念,因为这是 TS 功能
function simpleExample(nullableArg: number | undefined | null) {
const normal: number = nullableArg;
// Compile err:
// Type 'number | null | undefined' is not assignable to type 'number'.
// Type 'undefined' is not assignable to type 'number'.(2322)
const operatorApplied: number = nullableArg!;
// compiles fine because we tell compiler that null | undefined are excluded
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
85799 次 |
| 最近记录: |