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

TypeScript如何实现基于映射递归替换对象键的泛型类型

TypeScript 递归对象键重映射泛型实现

核心实现代码

首先修正示例中枚举的语法笔误(原otherkey = "otherkey2缺失闭合引号),完整泛型实现如下:

enum Mapping {
  foo = "foo2",
  bar = "bar2",
  otherkey = "otherkey2",
  // 其余预设映射属性...
}

type GenericType<T> = T extends object
  ? T extends (infer U)[]
    ? GenericType<U>[]
    : {
        [K in keyof T as K extends keyof typeof Mapping
          ? (typeof Mapping)[K]
          : K]: GenericType<T[K]>
      }
  : T;

实现逻辑说明

  • 类型判断分层:首先判断传入类型是否为对象类型,基础类型(string/number/boolean/函数等)直接返回原值,不做递归处理,避免死循环
  • 数组兼容:如果是数组类型,提取数组元素类型递归处理后,重新组装为同维度数组
  • 键重映射:通过TypeScript的键重映射语法as,遍历对象所有属性键,若键存在于Mapping枚举的键集合中,替换为枚举对应的值作为新键;不存在映射的键默认保留原名
  • 递归处理:所有属性值都会传入GenericType递归处理,支持任意层级的嵌套对象重映射
  • 版本兼容:该实现依赖TypeScript 4.1及以上版本支持的键重映射(Key Remapping)语法,低版本TS无法使用

效果验证

以基础输入类型和嵌套输入类型为例:

// 基础场景输入
type Input = {
  foo: string
  bar: string
}

// 嵌套场景输入
type NestedInput = {
  foo: string
  bar: {
    foo: number
    otherkey: boolean
    list: {
      bar: string
    }[]
  }
}

type BasicResult = GenericType<Input>
type NestedResult = GenericType<NestedInput>

其中BasicResult等价于:

{
  foo2: string
  bar2: string
}

NestedResult等价于:

{
  foo2: string
  bar2: {
    foo2: number
    otherkey2: boolean
    list: {
      bar2: string
    }[]
  }
}

完全符合需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 20:31:11