You need to enable JavaScript to run this app. TypeScript 如何定义 _embedded 内部属性名动态的泛型类型别名?
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript 如何定义 _embedded 内部属性名动态的泛型类型别名?

实现动态键名的泛型类型方案

完全可以实现动态绑定_embedded内部属性名的效果,核心是利用TypeScript的泛型键约束+映射类型能力,不需要额外的复杂语法。

核心实现思路

你之前的泛型只把数组元素类型作为参数,写死了Customers这个键名。要实现动态配置,只需要额外新增一个代表动态键名的泛型参数,配合映射类型能力,就能生成对应结构的类型:

  • 给代表键名的泛型参数加string类型约束,避免传入非字符串的非法键值
  • 通过映射类型语法把泛型键值转换成对象的实际属性名,对应的值就是你需要的数组类型,完全替代之前写死的Customers属性

具体代码实现

// K是动态键名泛型,约束为字符串;T是数组元素类型泛型
type MyType<K extends string, T> = {
  _embedded: {
    // 映射类型写法,把K作为对象的实际属性名
    [prop in K]: Array<T>
  }
}

实际使用示例

对应你提到的两类接口场景,可以直接复用同一个泛型:

  1. 客户列表接口场景
    // 定义单条客户数据的类型
    type Customer = {
      CompanyName: string
    }
    // 传入动态键名"Customers",元素类型Customer
    type CustomerResponse = MyType<"Customers", Customer>
    
    生成的类型完全匹配第一个接口返回的_embedded.Customers结构。
  2. 商品列表接口场景
    // 定义单条商品数据的类型
    type Product = {
      SKU: string
    }
    // 传入动态键名"Products",元素类型Product
    type ProductResponse = MyType<"Products", Product>
    
    生成的类型完全匹配第二个接口返回的_embedded.Products结构。

常见注意点

  • 不要直接在对象类型里写[K]: Array<T>形式的计算属性,TypeScript不支持这种裸的动态键推导,必须通过[prop in K]的映射类型写法,才能正确把泛型值转换成对象属性名
  • 如果需要兼容_embedded下存在其他额外属性的场景,可以在映射类型后面加交叉类型扩展:
    type MyType<K extends string, T> = {
      _embedded: {
        [prop in K]: Array<T>
      } & Record<string, unknown>
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.29 07:15:08