问题描述
简单的问题,给定一些 TypeScript:
function runInnerHTML () {
const container = document.getElementById('test-inner-html')
invariant(container)
beginTest(container)
}
function beginTest (el: HTMLElement) {
...
}
{
"include": ["src","types"],"compilerOptions": {
"module": "esnext","target": "esnext","moduleResolution": "node","jsx": "preserve","baseUrl": "./","allowSyntheticDefaultImports": true,"importsNotUsedAsValues": "error","noEmit": true,"strict": true,"skipLibCheck": true,"forceConsistentCasingInFileNames": true,"resolveJsonModule": true,"useDefineForClassFields": true
}
}
TypeScript 可以很好地编译上述文件 ? 没有问题。至关重要的是,invariant
函数成功地将 document.getElementById
的返回值(即 HTMLElement | null
)缩小到仅 HTMLElement
。如果我删除不变行,编译将按预期失败。
然而,我的 VSCode 不满意,因为它不理解不变量所做的类型缩小。
我的理解是,intellisense 应该使用与构建过程相同的 TS 服务器。我错过了什么?
解决方法
好的——发生这个问题的原因是项目中使用的 TypeScript 是 4.x
,而 VSCode 使用的 TypeScript 版本是 3.x
,即使我的“全局”打字稿版本是 { {1}} VSCode 有它自己使用的内部版本。
为了解决这个问题,我添加了一个具有以下内容的工作区设置:
>=4.x
然后返回失败的文档并运行 VSCode 命令“TypeScript:选择 TypeScript 版本”。 — 现在可以选择正确版本的 TS:
这解决了缩小问题。有关这些配置选项的更多详细信息,请参阅in the TypeScript documentation.