Typescript derive union type from tuple/array values
is very informative.
const list = ['a', 'b', 'c'] as const; // TS3.4 syntax
type NeededUnionType = typeof list[number]; // 'a'|'b'|'c';
Now, I try to make a type of Integer that has a range(0...255).
For an initial test, when [0,1,2,3]
is manually prepared, it works as expected.
const int3 = [0, 1, 2, 3] as const;
type Int3 = typeof int3[number];
// 0 | 1 | 2 | 3
const a: Int3 = 3; //ok, but error on >=4
However, when [0,1,..,255]
is prepaired with Array.keys() iteration, it won't work...
const int255 = [...Array(255).keys()] as const; // [0,1,..,255]
type Int255 = typeof int255[number];
const colorCode: Int255 = 300; //ok to compile,should be error
Is there any fix on this? Thanks.
Related topic here:
Is it possible to restrict number to a certain range
is not answered to question and it's TypeScript2.0 age(more than 5 years ago)