Sometimes we want to limit the range of numbers... Master advanced TypeScript type manipulation in this medium-level challenge on TypeScriptPro.
In this medium-level challenge, you'll implement NumberRange<L, H>, a type that produces a union of all integer literal types from L to H inclusive.
Sometimes we want to limit the range of numbers... For examples.
[object Object]Change the following code to make the test cases pass (no type check errors).
type Result1 = 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
type Result2 = 0 | 1 | 2
type Result3 =
| 0
| 1
| 2
| 3
| 4
| 5
| 6
| 7
| 8
| 9
| 10
| 11
| 12
| 13
| 14
| 15
| 16
| 17
| 18
| 19
| 20
| 21
| 22
| 23
| 24
| 25
| 26
| 27
| 28
| 29
| 30
| 31
| 32
| 33
| 34
| 35
| 36
| 37
| 38
| 39
| 40
| 41
| 42
| 43
| 44
| 45
| 46
| 47
| 48
| 49
| 50
| 51
| 52
| 53
| 54
| 55
| 56
| 57
| 58
| 59
| 60
| 61
| 62
| 63
| 64
| 65
| 66
| 67
| 68
| 69
| 70
| 71
| 72
| 73
| 74
Unlock 102+ medium, hard, and extreme challenges to master advanced TypeScript.
One-time payment. Lifetime access.
type NumberRange<
L extends number,
H extends number,
Arr extends any[] = [],
Result extends number = never
> = Arr['length'] extends H
? Result | H
: Arr['length'] extends L
? NumberRange<L, H, [...Arr, any], Result | Arr['length']>
: Result extends never
? NumberRange<L, H, [...Arr, any], Result>
: NumberRange<L, H, [...Arr, any], Result | Arr['length']>;How it works:
Arr as a counter, where Arr['length'] represents the current number being evaluatedResult accumulator that collects the union of all numbers in rangeArr['length'] equals H (the upper bound), it returns Result | H to include the upper bound and stop recursionArr['length'] equals L (the lower bound), it begins accumulating by adding Arr['length'] to Result and continuingResult extends never determines whether accumulation has started: if Result is still never, the current number is below L and should be skipped; otherwise, the current number is within range and gets added[...Arr, any]), effectively incrementing the counter until H is reachedAn alternative cleaner approach:
type MakeTuple<N extends number, T extends any[] = []> =
T['length'] extends N ? T : MakeTuple<N, [...T, any]>;
type NumberRange<L extends number, H extends number, T extends any[] = MakeTuple<L>> =
T['length'] extends H
? H | L
: T['length'] extends L
? NumberRange<L, H, [...T, any]> | T['length']
: NumberRange<L, H, [...T, any]> | T['length'];This challenge helps you understand tuple-based type-level counting and union accumulation, and how to apply these concepts in real-world scenarios.
This challenge is originally from here.