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

在TypeScript中如何从对象数组提取对象值作为联合类型?

从对象数组中提取键的联合类型

要提取数组中所有key字段的字面量联合类型,核心是让TypeScript保留具体的字符串字面量类型,而不是默认拓宽为string,具体实现步骤如下:

  1. 为数组添加as const断言
    这个断言会让TypeScript将数组及其元素标记为只读,同时保留每个key的具体字面量值:

    const myObj = [
      { key: 'orange', value: 1 },
      { key: 'apple', value: 1 }
    ] as const;
    
  2. 通过类型索引提取联合类型
    使用TypeScript的类型索引能力,逐层获取目标类型:

    type FruitKey = typeof myObj[number]['key'];
    // 此时 FruitKey 的类型为 'orange' | 'apple'
    

原理说明

  • typeof myObj获取数组的只读类型,typeof myObj[number]会得到数组中所有元素的类型联合(即{ readonly key: 'orange'; readonly value: 1; } | { readonly key: 'apple'; readonly value: 1; })。
  • 再通过['key']索引访问该联合类型的key属性,最终得到所有key值的字面量联合类型。

可选:封装通用类型工具

如果需要复用这个逻辑,可以封装一个通用类型:

type ExtractKeyFromArray<T extends readonly { key: string }[]> = T[number]['key'];

// 使用示例
type FruitKey = ExtractKeyFromArray<typeof myObj>;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 11:02:05