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
What does !: mean in Typescript?
提问by Sinosaurus
回答by Harshal Patil
There will be a scenario when TypeScript believes that certain property, variable will be null
or 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 a
may be null since there is no guarantee for this element to exists. So before you can access that variable, you have put in if
guard. 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 !: sometype
informs typescript not to worry about checking if varname
might be unassigned (it tells typescript that varname
will 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