【发布时间】:2021-02-07 05:48:13
【问题描述】:
VS 代码版本:
我正在 VS Code 中尝试一些“类型缩小”代码,但 VS Code 提供的信息类型与 TypeScript Playground 不同:
VS Code 给出:
Document.getElementById 的返回类型为HTMLElement:
TypeScript Playground 提供:
Document.getElementById 的返回类型应该是HTMLElement | null:
el 之前的 null 检查预计为 HTMLElement | null 类型:
el 经过 null 检查后的类型应为 HTMLElement 类型缩小:
我已经将全局 typescript 包升级到 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 中是否缺少某些配置?
【问题讨论】:
-
在 VSCode 底部的状态栏中,您应该会看到一个 TypeScript 版本号。如果单击它,您应该会看到命令提示符。选项之一是“打开 TSConfig”。您可以选择该选项并验证它指向正确的文件吗?
-
@lazytype 谢谢,通过在项目的根目录下创建一个 tsconfig.json 并将
strict设置为 true 解决了问题。 -
如果设置
strict: true,则不必指定单独的标志。见这里:typescriptlang.org/tsconfig#strict