Created
February 9, 2021 00:32
-
-
Save MurkyMeow/dde2e5c3a5507fecb510e076edcaf904 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type NumberRange<N extends number, A extends number[] = []> = | |
A['length'] extends N ? A : NumberRange<N, [...A, A['length']]> | |
type Upto10 = NumberRange<10> // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] | |
// If TS is too lazy to unwind a deep recursion (depth = 46): | |
type Upto46_ = NumberRange<46> // Type instantiation is excessively deep and possibly infinite | |
// We can reduce it's depth by specifying a bigger initial array (now depth = 36): | |
type Upto46 = NumberRange<46, NumberRange<10>> // [0, 1, 2, 3, 4, ..., 45] | |
// So the range can be as big as you want | |
type Upto100 = NumberRange<100, NumberRange<55, NumberRange<45>>> // [0, 1, 2, 3, 4, ..., 99] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type ValuesOf<T> = T extends (infer R)[] ? R : never | |
type NumberRange<N extends number, A extends number[] = []> = | |
A['length'] extends N ? ValuesOf<A> : NumberRange<N, [...A, A['length']]> | |
type Upto10 = NumberRange<10> // 0 | 1 | 2 | 3 | 4 |5 | 6 | 7 | 8 | 9 | |
type Between20And10 = Exclude<NumberRange<21>, NumberRange<10>> // 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment