ABOS
ABOS

Reputation: 3823

How to get union types of object values inside array?

For example, I have an array

const list = [{id: 'a'}, {id: 'b'}, {id: 'c'}] as const;

and I want to get union type from all values of field id, i.e. 'a'|'b'|'c'.

Upvotes: 2

Views: 160

Answers (1)

Nick
Nick

Reputation: 16576

You can use typeof list[number]["id"] to get a union of all the id values.

const list = [{id: 'a'}, {id: 'b'}, {id: 'c'}] as const;
type Values = typeof list[number]["id"];

Upvotes: 2

Related Questions