Zuc*_*jet 8 javascript typescript eslint tslint
typescript 源代码undefined!在很多地方使用。例如,在binder.ts 中,从第 261 行到第 271 行:
file = undefined!;
options = undefined!;
languageVersion = undefined!;
parent = undefined!;
container = undefined!;
thisParentContainer = undefined!;
blockScopeContainer = undefined!;
lastContainer = undefined!;
delayedTypeAliases = undefined!;
seenThisKeyword = false;
currentFlow = undefined!;
Run Code Online (Sandbox Code Playgroud)
从打字稿官方文档中,后缀的!意思是“非空断言运算符”,它的定义是:
一个新的!后缀表达式运算符可用于在类型检查器无法得出结论的上下文中断言其操作数为非空和非未定义
所以这种用法undefined!似乎没有意义,因为它断言 undefined 是非未定义的。
是什么意思undefined!,为什么我们这样使用?
所以这个用法未定义!似乎没有意义,因为它断言 undefined 是非未定义的。
undefined! 是什么意思,为什么我们这样使用?
另一种说法是,告诉打字稿“闭嘴,我知道我在做什么”。如果strictNullChecks打开,Typescript 将在将undefined/分配给null类型不包含undefined/的值时报错null。
strictNullChecks是一个很好的默认值,但在某些情况下,您可能想要分配undefined或null无论如何(可能在本地范围或库的私有部分中),并且您自己保证您将始终确保稍后设置值。
好处是库的用户不必处理可选属性,并且作为库作者,您可能在对象离开库边界之前如何构建对象具有更大的灵活性。
例子:
type MyArticle = {
title: string;
}
function getArticle(): MyArticle {
const result:MyArticle = {
// ignore the undefined error, we're dealing with this later.
title: undefined!,
};
result.title = 'Hello world';
return result;
}
Run Code Online (Sandbox Code Playgroud)
上面的例子是人为的。有更好的方法来构建它,我怀疑您共享的示例也是如此。
| 归档时间: |
|
| 查看次数: |
254 次 |
| 最近记录: |