supersize
supersize

Reputation: 14773

Declare literal union type based on array of objects values

Assuming I have an array of objects (simplified version):

const arrObj = [
  { id: "example1", other: "just" },
  { id: "example2", other: "an" },
  { id: "example3", other: "example" }
]

and I want to create a union type out of all ids

I tried:

const list = arrObj.map((item) => item.id) as const;
type ids = typeof list[number];

But this does not work as it seems I cannot create the array dynamically:

A 'const' assertions can only be applied to references to enum members, or string, number, boolean, array, or object literals.

The desired type output should be: "example1" | "example2" | "example3"

Upvotes: 0

Views: 37

Answers (1)

Matthieu Riegler
Matthieu Riegler

Reputation: 54698

const arrObj = [
  { id: "example1", other: "just" },
  { id: "example2", other: "an" },
  { id: "example3", other: "example" }
] as const

type myIds = typeof arrObj[number]['id']

Playground

Upvotes: 1

Related Questions