如何获取TypeScript Playground光标悬停显示的完整展开类型信息
如何生成TypeScript Playground悬停时显示的完整展开类型到.d.ts文件
问题描述
在TypeScript Playground中,光标悬停在类型上时能看到编译器解析后的完整展开类型(比如示例中A会显示number | undefined),但通过tsc直接生成的.d.ts文件只会保留原始类型别名引用(如declare type A = SecondArg<F>;)。
示例源码:
type SecondArg<F> = F extends (a: any, b: infer B) => any ? B : never // 获取Array.slice的类型 type F = typeof Array['prototype']['slice'] type A = SecondArg<F> // 悬停时显示number | undefined
当前生成的.d.ts内容:
declare type SecondArg<F> = F extends (a: any, b: infer B) => any ? B : never; declare type F = typeof Array.prototype.slice; declare type A = SecondArg<F>;
期望的.d.ts输出:
declare type A = number | undefined;
尝试过自定义Expand类型工具,但无法在.d.ts中得到展开后的结果:
type Expand<T> = T extends infer O ? { [K in keyof O]: O[K] } : never; type ExpandedA = Expand<A>;
解决方法
1. 用TypeScript Compiler API编写自定义脚本
通过TypeScript提供的Compiler API,可以手动解析类型并输出展开后的声明。核心是利用TypeChecker获取类型的完整展开形式:
import * as ts from "typescript"; // 初始化编译程序 const program = ts.createProgram(["src/index.ts"], {}); const checker = program.getTypeChecker(); const sourceFile = program.getSourceFile("src/index.ts")!; // 遍历源文件中的类型别名 ts.forEachChild(sourceFile, (node) => { if (ts.isTypeAliasDeclaration(node)) { const type = checker.getTypeAtLocation(node.name); // 获取完整无截断的类型字符串 const expandedType = checker.typeToString( type, undefined, ts.TypeFormatFlags.NoTruncation ); console.log(`declare type ${node.name.text} = ${expandedType};`); } });
运行脚本后,将输出的内容整理为.d.ts文件即可。
2. 使用第三方Transformer或工具
借助现成的工具可以自动处理类型展开:
ts-transformer-expand-types:一款TypeScript transformer,生成.d.ts时会自动将类型别名展开为最终解析后的类型,需配合ts-loader或rollup-plugin-typescript2等构建工具配置使用。- API Extractor:微软官方的API提取工具,配置
api-extractor.json中的编译选项后,生成声明文件时可自动展开类型,同时支持API文档管理。
3. 利用TS Playground导出功能
在TypeScript Playground右上角点击「Export」,选择「Export as .d.ts」,部分场景下会直接导出展开后的类型声明(注意:对复杂递归类型的支持有限)。
注意事项
- 完全展开复杂或递归类型会导致
.d.ts体积骤增,降低可读性,需根据实际场景权衡使用。 - 第三方Transformer需要调整构建工具配置,确保其在编译流程中生效。
内容的提问来源于stack exchange,提问作者albertkao9
相关产品推荐
相关产品推荐

