typescript !对象方法之后的打字稿中的运算符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38874928/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 07:16:39  来源:igfitidea点击:

! operator in typescript after object method

objecttypescriptoperators

提问by user2032922

I have an object Xwith a method getY()returning an object Ywith a method a(), in typescript. What does it mean an expression like this one:

我有一个X带有方法getY()的对象,在打字稿中返回一个Y带有方法的对象a()。像这样的表达是什么意思:

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?

我猜!操作符是用来检查空值的,但它具体是如何工作的呢?语言中在哪里定义?

回答by Nitzan Tomer

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 newpage, here's what it says:

这是一个新的 typescript 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.

一个新的!后缀表达式运算符可用于在类型检查器无法推断出该事实的上下文中断言其操作数为非空和非未定义。具体来说,操作x!生成 x 类型的值,排除 null 和 undefined。类似于形式为 x 和 x 作为 T 的类型断言,! 非空断言运算符在发出的 JavaScript 代码中被简单地删除。

// 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 (!)

记录此功能存在一个问题:记录非空断言运算符 (!)