问题描述
VS代码版本:
我正在VS Code中尝试一些“类型缩小”代码,但是VS Code提供的信息类型不同于TypeScript游乐场:
VS Code提供:
Document.getElementById
的返回类型为HTMLElement
:
而TypeScript Playground提供:
Document.getElementById
的返回类型应为HTMLElement | null
:
el
在空检查之前应为HTMLElement | null
类型:
el
在类型为Narrow的情况下应为HTMLElement
类型,如:
我已经将全局打字稿包升级到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
。