首页 > 解决方案 > `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!,为什么我们这样使用?

标签: javascripttypescripteslinttslint

解决方案


所以这个用法未定义!似乎没有意义,因为它断言未定义是未定义的。

undefined! 的含义是什么,为什么我们要这样使用?

另一种说法是,告诉打字稿“闭嘴,我知道我在做什么”。如果strictNullChecks打开,Typescript 在将undefined/分配null给类型不包含undefined/的值时会报错null

strictNullChecks是一个很好的默认值,但在某些情况下,您可能想要分配undefinednull无论如何(可能在本地范围或库的私有部分中),并且您自己保证始终确保稍后设置值。

好处是库的用户不必处理可选属性,并且作为库作者,您可能对在对象离开库边界之前如何构建对象有更多的灵活性。

例子:

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;

}

上面的例子是人为的。有更好的方法来构建它,我怀疑您共享的示例也是如此。


推荐阅读