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

[object Object]

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

ChallengeSolution
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

Pro Challenge

Unlock 102+ medium, hard, and extreme challenges to master advanced TypeScript.

One-time payment. Lifetime access.

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