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

TypeScript编译时如何导出模块类型?解决类型定义缺失问题

如何让TypeScript模块编译后导出类型定义?

我编写了一个TypeScript模块,示例代码如下:

// src/index.ts
import {AwesomeOptions} from './interfaces/Awesome';
export default class Awesome {
  constructor(options: AwesomeOptions) {
    // cool stuff
  }
}
// src/interfaces/Awesome.d.ts
export interface AwesomeOptions {
  // stuff
}

编译该模块为JavaScript后,仅生成了.js文件,未导出类型定义。将其导入到其他TypeScript应用时无法获取对应类型信息,请问该如何解决?


解决方案:调整编译配置 + 声明类型入口

这个问题我碰到过好多次,本质就是TypeScript默认不会自动生成类型声明文件,咱们只需要调整几个配置就能搞定:

1. 修改tsconfig.json开启类型声明生成

在项目根目录的tsconfig.json里,确保开启以下关键选项:

{
  "compilerOptions": {
    "target": "ES2020", // 根据你的需求设置目标JS版本
    "module": "CommonJS", // 可选ESNext等模块规范
    "outDir": "./dist", // 编译产物输出目录
    "declaration": true, // 核心:开启类型声明文件生成
    "declarationDir": "./dist", // 类型文件输出目录,建议和JS产物同目录
    "strict": true, // 可选,但推荐开启严格模式保证类型安全
    "include": ["src/**/*"] // 确保覆盖所有源码文件,包括手动写的.d.ts
  }
}
  • declaration: true:告诉TypeScript编译时为每个.ts文件生成对应的.d.ts类型声明文件
  • declarationDir:指定类型文件的输出位置,方便后续统一发布
  • include:避免你的Awesome.d.ts被编译工具忽略

2. 在package.json中声明类型入口

编译完成后,得让其他TypeScript项目知道你的模块类型文件在哪。在package.json里添加types字段:

{
  "name": "your-awesome-module",
  "version": "1.0.0",
  "main": "./dist/index.js", // JS代码入口
  "types": "./dist/index.d.ts", // 类型声明入口
  "scripts": {
    "build": "tsc"
  }
}

如果你的模块支持ES模块和CommonJS双入口,也可以用exports字段更精准配置:

{
  "exports": {
    ".": {
      "types": "./dist/index.d.ts",
      "require": "./dist/index.js",
      "import": "./dist/index.mjs"
    }
  }
}

3. 重新编译模块

运行npm run build(或者直接执行tsc),此时dist目录下会同时生成.js和.d.ts文件。其他TypeScript项目安装你的模块后,就能自动获取到Awesome类和AwesomeOptions接口的类型提示了。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:54:17