javascript - 为什么打字稿将导入的变量识别为任何类型?
问题描述
我有以下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/**/*"]
}
解决方案
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'];
推荐阅读
- python - 我该怎么做才能从 JetBrains 获得正常的 Python REPL
- php - 使用运行的 PHO 隐藏字段
- python - skimage 最大图像分辨率(内存错误)
- sql - 重组数据;根据路线点生成路线位置概览
- redis - 为什么 dict_force_resize_ratio 在 redis 中默认为 5?
- javascript - 检测浏览器是否支持“@supports”?
- javascript - if/else 语句判断 iframe 是否为空
- keras - Keras Fixing Seed 对训练数据改组的影响
- javascript - 为什么onload会导致我的图像切换闪烁?
- .net - 用vb.Net创建BitmapDecoder和SoftwareBitmap的方法是什么