javascript - `undefined!` 在 typescript 中是什么意思?

标签 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!;
来自 typescript 官方文档,后缀 !表示“非空断言运算符”,它的定义是:

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


所以这个用法undefined!似乎没有意义,因为它断言未定义是未定义的。undefined!是什么意思,以及为什么我们以这种方式使用?

最佳答案

So this usage undefined! seems make no sense, because it asserts that undefined is non-undefined.


What is the meaning of undefined!, and why we use in that way ?


另一种说法是,告诉 typescript “闭嘴,我知道我在做什么”。如果 strictNullChecks开启时,Typescript 在分配 undefined 时会报错/null类型不包括 undefined 的值/null .strictNullChecks是一个很好的默认值,但在某些情况下您可能想要分配 undefinednull无论如何(可能在本地范围或库的私有(private)部分),并且您自己保证始终确保稍后设置值。
好处是库的用户不必处理可选属性,并且作为库作者,您可能在对象离开库边界之前如何构建对象有更多的灵 active 。
例子:
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 - `undefined!` 在 typescript 中是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65757254/

相关文章:

javascript - 循环元素javascript

node.js - TypeScript 需要 node.js 才能运行吗?

reactjs - 如何在保持类型非可选的同时抽象传递重复的子属性?

javascript - eslint no-unused-vars varIgnorePattern 不起作用

sublimetext3 - 如何让 Prettier 和 ESLint 协同工作?

javascript - Google Geochart (1.1) 工具提示样式

javascript - 如何获取放置在响应式 HTML 页面上的 Canvas 的宽度

javascript - JQuery 无法在 IE v8 以下版本上运行

typescript - ionic : How do I hide an element on load

node.js - Typescript eslint - 缺少文件扩展名 "ts"导入/扩展