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

求推荐可拆分嵌套TypeScript接口为独立接口的重构工具

拆分TypeScript嵌套内联接口为独立接口的工具与方案

以下几种工具和方法可以满足你将嵌套内联类型提取为独立接口的需求,尤其适合处理从JSON Schema生成的大型接口:

  • ts-morph 脚本批量处理
    这是最灵活的方案,通过操作TypeScript AST实现批量提取。你可以编写自定义脚本遍历接口的嵌套类型,自动生成独立接口并替换原引用。示例代码如下:

    import { Project, InterfaceDeclaration } from "ts-morph";
    
    const project = new Project();
    const sourceFile = project.addSourceFileAtPath("./your-interface-file.ts");
    
    // 递归提取嵌套类型为独立接口
    function extractNestedInterfaces(interfaceDecl: InterfaceDeclaration, baseName: string) {
      interfaceDecl.getProperties().forEach(prop => {
        const propType = prop.getType();
        // 判断是否为未命名的对象类型
        if (propType.isObject() && !propType.getSymbol()?.getDeclarations()?.some(d => d.isInterfaceDeclaration())) {
          // 生成新接口名称(基于父接口和属性名)
          const newInterfaceName = `${baseName}${prop.getName().charAt(0).toUpperCase()}${prop.getName().slice(1)}`;
          // 添加新接口
          const newInterface = sourceFile.addInterface({
            name: newInterfaceName,
            properties: propType.getProperties().map(p => ({
              name: p.getName(),
              type: p.getType().getText()
            }))
          });
          // 替换原属性类型为新接口
          prop.setType(newInterfaceName);
          // 递归处理新接口的嵌套类型
          extractNestedInterfaces(newInterface, newInterfaceName);
        }
      });
    }
    
    // 定位目标接口并执行提取
    const targetInterface = sourceFile.getInterface("A")!;
    extractNestedInterfaces(targetInterface, "A");
    
    // 保存修改后的文件
    sourceFile.saveSync();
    
  • VS Code 插件手动/半自动化处理
    像 TypeScript Toolbox、TS Refactor 这类插件提供了可视化的重构功能:选中嵌套的对象类型(比如你的示例中b对应的{ c: { d: string } }),右键选择「提取为接口」,插件会自动生成独立接口并替换原位置的类型引用。适合处理少量需要调整的嵌套类型。

  • CLI 工具批量处理
    部分CLI工具如 ts-refactor 支持批量扫描文件,自动识别并提取所有嵌套内联类型为独立接口。只需指定目标文件或目录,工具就能完成批量转换,适合处理大规模的接口文件。

对于从JSON Schema生成的大型接口,优先推荐ts-morph脚本或CLI工具,能大幅提升处理效率并保证一致性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 15:45:13