首页 > 解决方案 > 如何获取对象数组中给定对象键的所有文字值的并集?

问题描述

假设我有这个对象数组,作为静态数据(它在运行时永远不会改变):

const things = [
  { id: 'some-id-1', value: 3 },
  { id: 'some-id-2', value: 7 },
  { id: 'some-id-3', value: 7 },
]

我想要这样的类型:

type ThingId = 'some-id-1' | 'some-id-2' | 'some-id-3'

有没有办法从对象数组中推断出来? ThingId

为什么我希望能够做到这一点:所以我可以创建类似 的函数doSomethingWithThing(thingId: ThingId),TypeScript 强制它只能使用有效的 调用ThingId,而不是使用 any string

标签: typescript

解决方案


您需要使用as const才能让 typescript 将 id 视为其文字值而不是string.

const things = [
  { id: 'some-id-1', value: 3 },
  { id: 'some-id-2', value: 7 },
] as const;

type Result = (typeof things)[number]['id']

对你起作用吗? 操场


推荐阅读