How to get all possible values of a union type to an array (or the other way around)?

Viewed 1464

Example:

type X = 'a' | 'b';
const xVals = ??? X; // ['a', 'b']

Or the other way around (from a list of all possible values get a type which is a union of those all values from an array).

My goal is to have all possible values listed only once.

1 Answers

You can't go from a type to a value. You can go the other way, starting from a value you can get the type. The problem is that the array value ['a', 'b'] would be typed as string[] and the union of string literal types would be lost.

The solution to use a function in order to force the compiler to infer a string literal type for the specified values:

function stringTuple<T extends [string] | string[]>(...data: T): T {
    return data;
}

let xValues = stringTuple('a', 'b') // typed as ["a", "b"]
type x = typeof xValues[number] // 'a' | 'b' 
Related