【问题标题】:Why typescript recognizes imported variables as of type any?为什么打字稿将导入的变量识别为任何类型?
【发布时间】:2021-04-04 08:42:41
【问题描述】:

我有以下 2 个文件:

文件src/helpers.ts

const someHelperArray = ['value1', 'value2'] as const

module.exports = {
  someHelperArray
}

文件src/car.ts

const {
  someHelperArray
} = require('./helpers')

在文件car.ts 中,当我将鼠标悬停在someHelperArray 上时,我得到了这个打字稿类型分辨率:const someHelperArray: any 而不是我预期的文字类型('value1' | 'value2')。本质上,打字稿无法识别来自另一个文件的导入变量的类型。我尝试更改 tsconfig.json 设置但没有任何帮助。如何让 typescript 识别从其他文件导入的类型?

这是我的tsconfig.ts

{
    "compilerOptions": {
      "lib": ["dom", "es6", "scripthost", "esnext"],
      "moduleResolution": "node",
      "baseUrl": "src",
      "watch": true,
      "allowJs": true,
      "esModuleInterop": true,
      "module": "commonjs",
      "sourceMap": true,
      "inlineSources": true,
      "allowSyntheticDefaultImports": true,
      "noUnusedLocals": true,
      "noUnusedParameters": true,
      "noImplicitAny": true,
      "strictNullChecks": true,
      "resolveJsonModule": true,
      "experimentalDecorators": true
    },
    "exclude": ["node_modules", "**/*.spec.ts", "ts-out/**/*", "babel-out/**/*"]
  }
  

【问题讨论】:

  • 一旦我重构代码以使用 ES6 语法进行模块导入/导出,问题就消失了。

标签: javascript typescript types import export


【解决方案1】:

CommonJS 模块(带有require)不是静态可分析的,这意味着module 的内容在运行前是未知的。实际上,您可以编写任何类型的动态代码来分配它(即:Object.assign)。因此,如果您需要保留模块之间的类型,则必须将它们编写为 ES6 模块,因为它们是可静态分析的。请注意,它仅在最新版本的 Node.js 中受支持。

如果你想在源代码中继续使用 CommonJS 模块,你也可以有一个文件 src/helpers.js:

const someHelperArray = ['value1', 'value2'];

module.exports = {
  someHelperArray
}

还有一个像这样的src/helpers.d.ts

export const someHelperArray: ['value1', 'value2'];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-19
    • 2023-01-11
    • 2021-11-07
    • 1970-01-01
    • 2020-05-06
    • 2019-07-25
    相关资源
    最近更新 更多