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

What does `undefined!` means in typescript?

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是非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 ?

另一种表达方式是,告诉打字稿“闭嘴,我知道我在做什么”。如果 strictNullChecks 开启,当将 undefined/null 赋值给类型不包括 undefined/null 的值时,Typescript 会报错。

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

好处是库的用户不必处理可选属性,而作为库的作者,您可能对对象离开您的边界之前的构建方式有更多的灵活性图书馆。

示例:

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;

}

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