`undefined!` 在打字稿中是什么意思?

问题描述

打字稿源代码在很多地方使用 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! 是什么意思,为什么我们这样使用?

解决方法

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

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;

}

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