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

如何将TypeScript类型展开并导出为可复用的.d.ts文件?

可用的TypeScript类型展开工具与方案

以下几种工具和方案可以将TypeScript类型(包括z.infer推导的类型)展开至编译器可推断的最大程度,并导出为可复用的.d.ts文件:

1. 自定义脚本(基于ts-morph)

通过ts-morph操作TypeScript AST,可精准控制类型展开逻辑,适合需要自定义处理的场景:

首先安装依赖:

npm install ts-morph typescript --save-dev

创建脚本expand-types.ts:

import { Project, TypeFormatFlags } from "ts-morph";

const project = new Project({ tsConfigFilePath: "./tsconfig.json" });
const sourceFile = project.getSourceFile("src/index.ts")!;
const outputFile = project.createSourceFile("dist/index.d.ts", "", { overwrite: true });

// 遍历所有导出的类型别名并展开
sourceFile.getExportedDeclarations().forEach(([name, decls]) => {
  const decl = decls[0];
  if (decl.isTypeAliasDeclaration()) {
    const expandedType = decl.getType().getText(sourceFile, {
      formatFlags: TypeFormatFlags.NoTruncation 
                  | TypeFormatFlags.IncludeTypeArguments 
                  | TypeFormatFlags.WriteTypeArgumentsOfSignature
    });
    outputFile.addTypeAlias({ name, type: expandedType, isExported: true });
  }
});

outputFile.save().then(() => console.log("展开后的声明文件已生成"));

运行脚本:

npx ts-node expand-types.ts

2. dts-bundle-generator(CLI工具)

专门用于生成精简且展开后的声明文件,支持自动处理类型别名和z.infer:

安装依赖:

npm install dts-bundle-generator --save-dev

执行命令生成展开后的.d.ts:

dts-bundle-generator --expand-alias src/index.ts -o dist/index.d.ts

3. @microsoft/api-extractor

适用于大型项目,不仅能展开类型,还能生成API文档和规范的声明文件:

安装依赖:

npm install @microsoft/api-extractor --save-dev

创建api-extractor.json配置文件:

{
  "mainEntryPointFilePath": "./src/index.ts",
  "dtsRollup": {
    "untrimmedFilePath": "./dist/index.d.ts"
  },
  "compiler": {
    "preserveWatchProgram": true
  }
}

运行命令生成文件:

npx api-extractor run

以上方案均能处理你提到的场景:将z.infer<typeof Foo>展开为实际的{ bar: string; },生成的.d.ts文件可直接被其他项目引用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 15:01:14