#8640Medium

Number Range

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.

Challenge Instructions: Number Range

Medium

Sometimes we want to limit the range of numbers... For examples.

type result = NumberRange<2 , 9> //  | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9

Change the following code to make the test cases pass (no type check errors).

Loading...

Detailed Explanation

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:

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

Share this challenge

Join early, learn faster.

Be the first to access the course, unlock exclusive launch bonuses, and get special early-bird pricing before anyone else.

No spam, unsubscribe at any time. We respect your privacy.

Limited Availability

Only 27 Spots left

Early Access

Get 1 month early access

>75% Off

Pre-Launch discount