为什么从 VS Code 中 Document.getElementById 的返回类型中删除了“null”?

azt*_*ack 10 typescript type-narrowing

VS代码版本:

VS 代码版本

我正在 VS Code 中尝试一些“Type Narrowing”代码,但 VS Code 提供的信息类型与 TypeScript Playground 不同:

VS Code 给出:的返回类型Document.getElementByIdHTMLElement

VS代码

VS代码

而 TypeScript Playground 提供:

的返回类型Document.getElementById应该是HTMLElement | null在此处输入图片说明

el在空检查预计为类型之前HTMLElement | null

在此处输入图片说明

el在空检查之后应该是类型HTMLElement缩小的类型:

在此处输入图片说明

我已经升级了全球打字稿包V4.0.2并设置typescript.tsdk/Users/<username>/.nvm/versions/node/v12.16.3/lib/node_modules/typescript/lib用户settings.json

我已将严格的类型检查选项设置为:

    /* Strict Type-Checking Options */
    "strict": true,
    // "noImplicitAny": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    // "strictBindCallApply": true,
    // "strictPropertyInitialization": true, 
    // "noImplicitThis": true,
    "alwaysStrict": true,
Run Code Online (Sandbox Code Playgroud)

有没有我遗漏的配置tsconfig.json

Brh*_*aka 3

根据VS 代码文档

通常,任何新 TypeScript 项目的第一步都是添加tsconfig.json文件。文件tsconfig.json定义TypeScript项目设置,例如编译器选项和应包含的文件。为此,请打开要存储源代码的文件夹并添加一个名为. 进入此文件后,IntelliSense (Ctrl+Space) 将全程为您提供帮助。tsconfig.json

因此,该tsconfig.json文件应位于项目的根目录中。解决问题的另一个步骤是添加"strict": true新创建的tsconfig.json文件。