【问题标题】:VSCode TypeScript intellisense is not type narrowingVSCode TypeScript 智能感知不是类型缩小
【发布时间】:2021-04-23 02:48:05
【问题描述】:

简单的问题,给出一些 TypeScript:


function runInnerHTML () {
  const container = document.getElementById('test-inner-html')
  invariant(container)
  beginTest(container)
}

function beginTest (el: HTMLElement) {
...
}

还有一个tsconfig.json

{
  "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 | nullHTMLElement。如果我删除不变行,编译会按预期失败。

但是,我的 VSCode 不满意,因为它不理解不变量正在做的类型缩小。

我的理解是智能感知应该使用与构建过程相同的 TS 服务器。我错过了什么?

【问题讨论】:

    标签: typescript visual-studio-code vscode-settings


    【解决方案1】:

    好的 - 发生此问题的原因是项目中使用的 TypeScript 是 4.x,而 VSCode 使用的 TypeScript 版本是 3.x,即使我的“全局”打字稿版本是 >=4.x VSCode它使用的是自己的内部版本。

    为了解决这个问题,我添加了一个工作区设置,内容如下:

    {
        "typescript.tsdk": "./node_modules/typescript/lib"
    }
    

    然后返回失败的文档并运行 VSCode 命令“TypeScript:选择 TypeScript 版本”。 — 现在可以选择正确版本的 TS:

    这解决了缩小问题。有关这些配置选项的更多详细信息,请访问in the TypeScript documentation.

    【讨论】:

      猜你喜欢
      • 2022-07-04
      • 1970-01-01
      • 1970-01-01
      • 2020-02-06
      • 1970-01-01
      • 2016-12-28
      • 2019-11-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多