【问题标题】:Why is 'null' removed from return type of Document.getElementById in VS Code?为什么在 VS Code 中从 Document.getElementById 的返回类型中删除了“null”?
【发布时间】: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

标签: typescript type-narrowing


【解决方案1】:

根据VS Code Docs

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

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

【讨论】:

    猜你喜欢
    • 2011-02-07
    • 1970-01-01
    • 2017-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多