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

如何在TypeScript中移除嵌套对象的body包装并保留结构

移除TypeScript嵌套对象中所有body包装并保留结构

可以通过递归的TypeScript类型实现需求——移除任意深度嵌套对象里的body包装,同时完整保留原有的层级结构。

核心递归类型

// 递归处理对象,移除所有层级的body包装
type UnwrapBody<T> = 
  // 如果当前类型包含body属性,合并原类型(去掉body)和body内部的类型,再递归处理
  T extends { body: infer U }
    ? UnwrapBody<Omit<T, 'body'> & U>
    // 如果是对象但没有body,遍历每个属性递归处理
    : T extends object
      ? { [K in keyof T]: UnwrapBody<T[K]> }
      // 非对象类型直接返回
      : T;

测试示例

用你提供的TestInterface做测试:

type TestInterface = {
  id: string
  body: {
    title: string 
    something: string 
    user: {
      id: string
      body: {
        firstname: string
        lastname: string
        age: number
      }
    }
    country: {
      id: string
      body: {
        code: string
        name: string
        region: {
          id: string
          body: {
            code: string
            name: string
            continent: {
              id: string
              body: {
               code: string
               name: string
              }
            }
          }
        }
      }
    }
  }
};

// 生成处理后的类型
type UnwrappedTestInterface = UnwrapBody<TestInterface>;

此时UnwrappedTestInterface的结构完全符合你的期望:

type UnwrappedTestInterface = {
  id: string;
  title: string;
  something: string;
  user: {
    id: string;
    firstname: string;
    lastname: string;
    age: number;
  };
  country: {
    id: string;
    code: string;
    name: string;
    region: {
      id: string;
      code: string;
      name: string;
      continent: {
        id: string;
        code: string;
        name: string;
      };
    };
  };
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 21:25:17