首页 > 解决方案 > 为什么打字稿将导入的变量识别为任何类型?

问题描述

我有以下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/**/*"]
  }
  

标签: javascripttypescripttypesimportexport

解决方案


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'];

推荐阅读