!对象方法后在打字稿中使用运算符 [英] ! operator in typescript after object method
问题描述
我有一个对象X
,它带有方法getY()
,并用打字稿返回了带有方法a()
的对象Y
.
这是什么意思?
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()!.a()
我猜想!
运算符用于检查null,但是它具体如何工作?语言在哪里定义?
I guess the !
operator is used to check against null, but how does it work concretely? Where is defined in the language?
推荐答案
它称为非null断言运算符",它告诉编译器x.getY()
不为null.
It's called the "Non-null assertion operator" and it tells the compiler that x.getY()
is not null.
这是TypeScript 2.0的一项新功能,您可以在新页面,内容如下:
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:
一个新的!修复后表达式运算符可用于断言其 在以下类型的上下文中,操作数是非null和undefined的: 检查者无法得出结论.具体来说,操作 X!产生x类型的值,其中排除了null和undefined. 类似于形式为x和x的类型断言,即T! 非null断言运算符被简单地删除在发出 JavaScript代码.
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.
// 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 (!)
这篇关于!对象方法后在打字稿中使用运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!