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