如何将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
相关产品推荐
相关产品推荐

