You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CommonJS模块TypeScript类型无法传递至require调用文件的问题解决

TypeScript CommonJS模块require引入丢失类型的解决方案

问题场景

  • 在scripts/ci/publish/getTag.ts模块中定义了Release类型,以及返回该类型的getTag函数,通过module.exports导出
  • 在scripts/ci/publish/index.ts中使用require引入该模块并调用getTag后,接收返回值的变量tag类型被推断为any,而非预期的Release类型
  • 代码通过ts-node可以正常执行,但类型推断不符合预期

问题根源

TypeScript对CommonJS模块的require导入存在类型解析限制:当模块通过module.exports导出内容时,require引入无法让TypeScript正确识别导出的类型信息,最终导致类型推断失效,变量被标记为any。

解决步骤

1. 替换require为ES模块import语法

将index.ts中的require引入改为标准ES模块的import:

// 原require写法
const { getTag } = require('./getTag');

// 修改后的import写法
import { getTag } from './getTag';

2. 配置tsconfig.json启用esModuleInterop

在tsconfig.json的compilerOptions中添加esModuleInterop: true,确保TypeScript能正确处理CommonJS与ES模块的互操作,同时保留类型信息:

{
  "compilerOptions": {
    // 其他已有配置...
    "esModuleInterop": true
  }
}

内容的提问来源于stack exchange,提问作者Ashley Coolman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 09:52:02