javascript - `undefined!` 在打字稿中是什么意思?
问题描述
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!;
从打字稿官方文档,后缀的!
意思是“非空断言运算符”,它的定义是:
一个新的!后缀表达式运算符可用于在类型检查器无法得出结论的上下文中断言其操作数为非空且非未定义
所以这种用法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;
}
上面的例子是人为的。有更好的方法来构建它,我怀疑您共享的示例也是如此。
推荐阅读
- javascript - 如何过滤 Reactjs 的 JSON 输出?
- performance - Clojure comp 不进行尾调用优化(可以创建 StackOverflow 异常)
- spring-cloud-dataflow - 如何修复 Spring Cloud Data Flow Kubernetes 容器就绪探测失败:HTTP 探测失败,状态码:401
- reactjs - 主页与其他页面重叠使用 React Route
- django - 带有电话号码的 URL django
- file - julia1.1.0中如何使用IOBuffer读取文件?
- c++ - 如何在 Sentry 本地版本中创建 CPP 项目
- android - 用于群聊活动的 RecyclerView 未显示在 Android Studio 的 FirebaseUI 中
- c++ - 如何将字符数组转换为字符串?
- python-3.x - 循环直到屏幕改变