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

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

实现方法

要提取数组中对象的key值作为TypeScript联合类型,需要借助as const断言保留字面量类型,再通过类型查询获取目标联合类型:

  1. 给原数组添加as const断言
const temp = [
  { key: "name", value: "mike" },
  { key: "gender", value: "male" },
] as const;
  1. 定义联合类型
type TempKey = typeof temp[number]['key'];
// 此时 TempKey 的类型为 "name" | "gender"

原理说明

  • 默认情况下TypeScript会把key的类型推断为宽泛的string,as const断言会强制TypeScript将数组及内部对象转为只读字面量类型,保留key的具体字符串值。
  • typeof temp[number] 获取数组所有元素的联合类型,再通过['key']提取该联合类型中key属性的类型,最终得到目标联合类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 04:31:02