TypeScript tip: It's often helpful to access a union type at runtime


TypeScript tip:

It's often helpful to access a union type at runtime.

Solution?
1. Declare an array const
2. Use typeof to derive a union from the array.

const letters = ['a', 'b'] as const;
type UnionType = typeof letters[number]; // "a" | "b";
Common question: Why is the [number] necessary at this spot?

// typeof letters[number]

Answer: This says, iterate over the array, and generate a type for each index in the array. We say number because array indexes have a type of number.

View original on X