I have an object X
with a method getY()
returning an object Y
with a method a()
, in typescript. What does it mean an expression like this one:
我有一个对象X,方法getY()在typescript中用方法a()返回一个对象Y.这样的表达是什么意思:
X.getY()!.a()
I guess the !
operator is used to check against null, but how does it work concretely? Where is defined in the language?
我想是的!运算符用于检查null,但具体如何工作?语言中定义的位置是什么?
1 个解决方案
#1
24
It's called the "Non-null assertion operator" and it tells the compiler that x.getY()
is not null.
它被称为“非空断言运算符”,它告诉编译器x.getY()不为空。
It's a new typescript 2.0 feature and you can read about it in the what's new page, here's what it says:
这是一个新的打字稿2.0功能,您可以在新页面中阅读它,这是它的内容:
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 x and x as T, the ! non-null assertion operator is simply removed in the emitted JavaScript code.
一个新的! post-fix表达式运算符可用于断言其操作数在类型检查器无法推断该事实的上下文中为非null且非未定义。具体来说,操作x!生成x类型的值,其中包含null和undefined。类似于形式x和x的类型断言为T,!在发出的JavaScript代码中简单地删除了非null断言运算符。
// Compiled with --strictNullChecks
function validateEntity(e?: Entity) {
// Throw exception if e is null or invalid entity
}
function processEntity(e?: Entity) {
validateEntity(e);
let s = e!.name; // Assert that e is non-null and access name
}
Edit
There's an issue for documenting this feature: Document non-null assertion operator (!)
记录此功能存在一个问题:记录非空断言运算符(!)
#1
24
It's called the "Non-null assertion operator" and it tells the compiler that x.getY()
is not null.
它被称为“非空断言运算符”,它告诉编译器x.getY()不为空。
It's a new typescript 2.0 feature and you can read about it in the what's new page, here's what it says:
这是一个新的打字稿2.0功能,您可以在新页面中阅读它,这是它的内容:
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 x and x as T, the ! non-null assertion operator is simply removed in the emitted JavaScript code.
一个新的! post-fix表达式运算符可用于断言其操作数在类型检查器无法推断该事实的上下文中为非null且非未定义。具体来说,操作x!生成x类型的值,其中包含null和undefined。类似于形式x和x的类型断言为T,!在发出的JavaScript代码中简单地删除了非null断言运算符。
// Compiled with --strictNullChecks
function validateEntity(e?: Entity) {
// Throw exception if e is null or invalid entity
}
function processEntity(e?: Entity) {
validateEntity(e);
let s = e!.name; // Assert that e is non-null and access name
}
Edit
There's an issue for documenting this feature: Document non-null assertion operator (!)
记录此功能存在一个问题:记录非空断言运算符(!)