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

如何将对象数组转换为对象name属性值的联合类型?

如何将对象数组转换为对象name属性的联合类型

你当前的代码没法得到目标联合类型,原因是all被TypeScript推断成了普通的{name: string; id: number}[],map返回的结果类型是string[],即便加了as const也没法把泛化的string转换成具体的字面量值。

下面给你两种可行的实现方案:

方案一:将数组定义为只读字面量数组(推荐,类型最精准)

const a = {
  name: "a",
  id: 0
} as const;
const b = {
  name: "b",
  id: 1
} as const;
const c = {
  name: "c",
  id: 2
} as const;
const all = [a, b, c] as const;
type t = typeof all[number]["name"]; // 最终类型为 "a" | "b" | "c"

通过as const把每个对象和数组都标记为只读字面量类型,TypeScript会完整保留所有具体的字符串和数值字面量,之后通过typeof all[number]["name"]就能提取数组中所有元素的name属性类型,自动组成联合类型。

方案二:保留数组的可变性(允许后续修改数组)

// 先给每个对象的name指定字面量类型
const a = { name: "a" as const, id: 0 };
const b = { name: "b" as const, id: 1 };
const c = { name: "c" as const, id: 2 };

// 显式声明数组类型为这些对象的联合类型集合
const all: (typeof a | typeof b | typeof c)[] = [a, b, c];
type t = typeof all[number]["name"]; // 最终类型为 "a" | "b" | "c"

先让每个对象的name属性锁定为具体字面量类型,再把all的类型声明为这些对象的联合类型数组,这样TypeScript就能识别出name的具体取值范围,进而生成对应的联合类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 23:27:05