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

如何生成无外部依赖的合并TypeScript类型文件?

如何从已有TypeScript类型生成无依赖的独立类型?

需求场景

假设你有以下相互依赖的TypeScript类型文件:

  • A.ts
export type A_Type = { some: string }
  • B.ts
export type B_Type = { someOther: string }
  • C.ts
import type { A_Type } from './A.ts'
import type { B_Type } from './B.ts'

export type C_Final = A_Type | B_Type

需要生成一个包含所有依赖类型内容的独立文件,最终输出示例:

export type C_Final = { some: string } | { someOther: string }

自动化解决方案

方法1:使用rollup-plugin-dts

这是最常用的类型合并工具,可自动将依赖类型内联到最终声明文件中:

  1. 安装依赖:
npm install --save-dev rollup rollup-plugin-dts typescript
  1. 创建rollup.config.js配置文件:
import dts from 'rollup-plugin-dts';

export default {
  input: './C.ts',
  output: [{ file: './C_Compiled.d.ts', format: 'es' }],
  plugins: [dts()],
};
  1. 在package.json中添加执行脚本:
{
  "scripts": {
    "bundle-types": "rollup -c"
  }
}
  1. 运行命令生成文件:
npm run bundle-types

执行后会生成C_Compiled.d.ts,内容就是完全内联所有依赖类型的独立声明。

方法2:使用ts-morph编写自定义脚本

如果需要更灵活的类型处理逻辑,可使用ts-morph手动遍历并生成独立类型:

  1. 安装依赖:
npm install --save-dev ts-morph typescript
  1. 创建脚本文件bundle-types.ts:
import { Project, TypeFormatFlags } from 'ts-morph';

const project = new Project();
const sourceFile = project.addSourceFileAtPath('./C.ts');
const cFinalType = sourceFile.getTypeAlias('C_Final');

// 将类型格式化为无依赖的字符串
const formattedType = cFinalType?.getType().getText(sourceFile, {
  typeFormatFlags: TypeFormatFlags.NoTruncation | TypeFormatFlags.IncludeTypeArguments
});

// 生成独立类型文件
const outputFile = project.createSourceFile('./C_Compiled.d.ts', '', { overwrite: true });
outputFile.addTypeAlias({
  name: 'C_Final',
  type: formattedType || ''
});

outputFile.saveSync();
  1. 执行脚本:
npx ts-node bundle-types.ts

这种方法适合处理复杂类型场景,可自定义类型解析规则。

方法3:TypeScript编译器配合dts-bundle-generator(不推荐)

使用tsc --emitDeclarationOnly会生成保留导入的声明文件,可配合dts-bundle-generator工具合并依赖,但步骤相对繁琐,不如前两种方法高效。

注意事项

  • 确保tsconfig.json中启用declaration: true,部分工具需配合strict模式以正确解析类型。
  • 复杂类型(如泛型、条件类型)可被工具自动内联,但存在循环依赖的类型需手动调整结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 13:06:19