2

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'.

1 Answer 1

2

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"];
Sign up to request clarification or add additional context in comments.

4 Comments

I tried in playground, and it did not work, any specific TS settings you are using?
No, here's the playground link that's working for me: typescriptlang.org/play?#code/…
ah, I have a typo -- an extra comma in the array. so it works. thank you!
Great! No problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.