[英]Why typescript recognizes imported variables as of type any?
I have the following 2 files:我有以下2个文件:
File src/helpers.ts
:文件
src/helpers.ts
:
const someHelperArray = ['value1', 'value2'] as const
module.exports = {
someHelperArray
}
File src/car.ts
:文件
src/car.ts
:
const {
someHelperArray
} = require('./helpers')
In the file car.ts
when I hover over the someHelperArray
I get this typescript type resolution: const someHelperArray: any
instead of literal type I expected ( 'value1' | 'value2'
).在文件
car.ts
,当我在 someHelperArray 上进行someHelperArray
时,我得到了这个 typescript 类型解析: const someHelperArray: any
而不是我期望的文字类型( 'value1' | 'value2'
)。 Essentially typescript doesn't recognize the types of imported variables from another file.本质上 typescript 无法识别来自另一个文件的导入变量的类型。 I tried changing
tsconfig.json
settings but nothing helped.我尝试更改
tsconfig.json
设置,但没有任何帮助。 How to can I get typescript to recognize types imported from other files?如何让 typescript 识别从其他文件导入的类型?
This is my tsconfig.ts
:这是我的
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/**/*"]
}
A CommonJS module (with require
) is not statically analyzable, which means the content of module
is unknown before run time. CommonJS 模块(带有
require
)不是静态可分析的,这意味着module
的内容在运行之前是未知的。 Indeed, you could write any kind of dynamic code to assign it (ie: Object.assign
).实际上,您可以编写任何类型的动态代码来分配它(即:
Object.assign
)。 So if you need to retain the types between modules you have to write them as ES6 modules because these are statically analyzable.因此,如果您需要保留模块之间的类型,则必须将它们编写为 ES6 模块,因为它们是可静态分析的。 Note that it is supported in latest versions of Node.js only.
请注意,仅最新版本的 Node.js 支持它。
If you wanted to keep using CommonJS modules in the source code, you could also have one file src/helpers.js
:如果你想在源代码中继续使用 CommonJS 模块,你也可以有一个文件
src/helpers.js
:
const someHelperArray = ['value1', 'value2'];
module.exports = {
someHelperArray
}
And one src/helpers.d.ts
like this:一个
src/helpers.d.ts
是这样的:
export const someHelperArray: ['value1', 'value2'];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.