为什么打字稿将导入的变量识别为任何类型?
Why typescript recognizes imported variables as of type any?
我有以下 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'
)。本质上,typescript 无法识别从另一个文件导入的变量的类型。我尝试更改 tsconfig.json
设置但没有任何帮助。如何让打字稿识别从其他文件导入的类型?
这是我的 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'];
我有以下 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'
)。本质上,typescript 无法识别从另一个文件导入的变量的类型。我尝试更改 tsconfig.json
设置但没有任何帮助。如何让打字稿识别从其他文件导入的类型?
这是我的 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'];