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

TypeScript中如何实现KeyBy泛型 从对象数组生成指定属性键的对象类型

TypeScript 类型层面KeyBy实现

完整实现代码

// 兼容只读数组和普通数组,不需要兼容可去掉readonly修饰
type KeyBy<A extends readonly object[], S extends keyof A[number]> = {
  [K in A[number][S]]: Extract<A[number], Record<S, K>>
}

实现逻辑说明

  • A[number]:直接获取数组所有元素的联合类型,不需要手动遍历数字索引
  • A[number][S]:提取所有元素指定属性S的字面量值,作为生成对象的键的联合类型
  • Extract<A[number], Record<S, K>>:从元素联合类型中筛选出属性S等于当前键K的对应元素类型,保证键值一一匹配

测试示例

使用提供的测试用例验证:

type Arr = [
    {slug: 'test-1', value: string},
    {slug: 'test-2', value: string},
    {slug: 'test-3', value: string},
]

type Keyed = KeyBy<Arr, 'slug'>

得到的Keyed类型完全符合预期:

{
    'test-1': {slug: 'test-1', value: string},
    'test-2': {slug: 'test-2', value: string},
    'test-3': {slug: 'test-3', value: string},
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 16:24:02