typescript !: 在打字稿中是什么意思?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50983838/
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-10-21 05:29:34  来源:igfitidea点击:

What does !: mean in Typescript?

typescriptvue.js

回答by Harshal Patil

There will be a scenario when TypeScript believes that certain property, variable will be nullor undefined. But if you are sure that this variable cannot be null, then you can use this operator.

当 TypeScript 认为某些属性、变量将是null或时,会出现这种情况undefined。但是如果你确定这个变量不能为空,那么你可以使用这个操作符。

Consider the example:

考虑这个例子:

let a = document.getElementById('hello');

if (a) {
    a.style.width = '100px';
}

TypeScript assumes that variable amay be null since there is no guarantee for this element to exists. So before you can access that variable, you have put in ifguard. But if you know that your application is always going to have an HTML element with id #hello, then you can rewrite above code as:

TypeScript 假定变量a可能为 null,因为不能保证此元素存在。因此,在您可以访问该变量之前,您已经进行了if保护。但是如果你知道你的应用程序总是会有一个带有 id 的 HTML 元素#hello,那么你可以将上面的代码重写为:

const a = document.getElementById('hello');

a!.style.width = '100px';

The above code is more readable and less verbose. Read more here at https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-0.html

上面的代码更易读,更简洁。在此处阅读更多信息https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-0.html

EDIT: Technically correct comment by @Simon: Specifically, the operation x! produces a value of the type of x with null and undefined excluded.

编辑:@Simon 在技术上正确的评论:具体来说,操作 x!生成 x 类型的值,排除 null 和 undefined。

回答by iislucas

That is a "definite assignment assertion": varname !: sometypeinforms typescript not to worry about checking if varnamemight be unassigned (it tells typescript that varnamewill definitely be assigned, even if typescript cannot infer where it is assigned). Normally typescript will check if the variable may be unassigned, and gives errors.

这是一个“明确的赋值断言”:varname !: sometype通知打字稿不要担心检查是否varname可能未分配(它告诉打字稿varname肯定会被分配,即使打字稿无法推断它被分配的位置)。通常打字稿会检查变量是否可能未分配,并给出错误。

For more information, see: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#definite-assignment-assertions

有关更多信息,请参阅:https: //www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#define-assignment-assertions