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

如何在TypeScript的.d.ts文件中获取完整展开的类型信息

解决TypeScript .d.ts文件中类型别名未展开的问题

临时应急:手动展开+声明映射

  • 编译时开启--declaration和--declarationMap选项,生成的.d.ts.map文件会保留完整类型关联信息。
  • 在VS Code里按住Ctrl(Windows)/Cmd(Mac)点击.d.ts中的SecondArg<F>,跳转到定义处就能看到展开后的完整类型,直接复制替换掉别名引用即可。

工具辅助:用脚本强制替换类型

  • 安装tsc-alias工具:npm install -D tsc-alias(该工具更适合路径别名替换,固定工具类型场景下,写简单Node脚本更直接)。
  • 使用TypeScript Compiler API遍历.d.ts文件,将工具类型引用替换为解析后的具体类型,示例脚本(针对SecondArg场景):
    import * as ts from 'typescript';
    
    const targetFile = './dist/index.d.ts';
    const content = ts.readFileSync(targetFile, 'utf-8');
    const sourceFile = ts.createSourceFile(targetFile, content, ts.ScriptTarget.Latest);
    
    function traverse(node: ts.Node) {
      if (ts.isTypeAliasDeclaration(node)) {
        const typeStr = ts.createPrinter().printNode(ts.EmitHint.Type, node.type, sourceFile);
        if (typeStr.includes('SecondArg')) {
          // 生成展开后的类型节点
          const expandedTypeNode = ts.factory.createUnionTypeNode([
            ts.factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword),
            ts.factory.createKeywordTypeNode(ts.SyntaxKind.UndefinedKeyword)
          ]);
          const newAlias = ts.factory.createTypeAliasDeclaration(
            node.modifiers, node.name, node.typeParameters, expandedTypeNode
          );
          const newContent = ts.createPrinter().printNode(ts.EmitHint.Unspecified, newAlias, sourceFile);
          // 可直接写入文件,或输出到控制台复制使用
          console.log(newContent);
        }
      }
      ts.forEachChild(node, traverse);
    }
    
    traverse(sourceFile);
    
  • 运行脚本后,将输出内容替换原.d.ts文件中的对应类型。

源头根治:改写工具类型为内联形式

  • 如果SecondArg是自定义工具类型,不要单独定义它,直接将逻辑内联到目标类型中。比如原代码:
    type SecondArg<F> = F extends (a: any, b: infer B) => any ? B : never;
    type F = (x: string, y?: number) => void;
    type A = SecondArg<F>;
    
    改写为:
    type F = (x: string, y?: number) => void;
    type A = F extends (a: any, b: infer B) => any ? B : never;
    
    这样编译生成的.d.ts文件中,A的类型会直接显示为number | undefined。

进阶方案:自定义编译转换器

  • 编写TypeScript自定义转换器,在编译阶段自动将工具类型展开为具体类型。
  • 在tsconfig.json中配置transformers选项指定转换器路径,编译时自动处理,实现一劳永逸的类型展开。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 21:01:22