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.
type result = NumberRange<2 , 9> // | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9Change the following code to make the test cases pass (no type check errors).
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.
Be the first to access the course, unlock exclusive launch bonuses, and get special early-bird pricing before anyone else.
Only 27 Spots left
Get 1 month early access
Pre-Launch discount