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

问题描述

VS代码版本:

VS Code Version

我正在VS Code中尝试一些“类型缩小”代码,但是VS Code提供的信息类型不同于TypeScript游乐场:

VS Code提供: Document.getElementById的返回类型为HTMLElement

VS Code

VS Code

而TypeScript Playground提供:

Document.getElementById的返回类型应为HTMLElement | null

enter image description here

el在空检查之前应为HTMLElement | null类型:

enter image description here

el在类型为Narrow的情况下应为HTMLElement类型,如:

enter image description here

我已经将全局打字稿包升级到v4.0.2,并在用户settings.json中将typescript.tsdk设置为/Users/<username>/.nvm/versions/node/v12.16.3/lib/node_modules/typescript/lib

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

    /* Strict Type-Checking Options */
    "strict": true,// "noImplicitAny": true,"strictnullchecks": true,"strictFunctionTypes": true,// "strictBindCallApply": true,// "strictPropertyInitialization": true,// "noImplicitThis": true,"alwaysstrict": true,

tsconfig.json中是否缺少某些配置?

解决方法

根据VS Code Docs

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

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...