Typescript Numeric Range Type

So you want a numeric range type, for example, from 30–40

the usual way is


type Thirty_to_Forty = 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37| 38 | 39 |40

it is doable but 0 fun in it (for obvious reasons)

what if you want a meta solution, from any range to any range, is it even possible?

It is, here is how you do it

type CreateArrayWithLengthX<
LENGTH extends number,
ACC extends unknown[] = [],
> = ACC['length'] extends LENGTH
? ACC
: CreateArrayWithLengthX<LENGTH, [...ACC,1]>

type NumericRange<
START_ARR extends number[],
END extends number,
ACC extends number=never>
=START_ARR['length'] extends END
? ACC | END
: NumericRange<[...START_ARR,1], END, ACC | START_ARR['length']>

type TWENTY_TO_FORTY = NumericRange<CreateArrayWithLengthX<20>,40>

Playground

keep in mind that there is a limit to how deep Typescript can recurse, and that number is 1000

Typescript will complain if your starting number is 1000 or your range size is 1000.

--

--

Typescript Zombie. Youtube Pikachu On Acid. (Unrelated to programming but by watching it you become a good developer overnight)

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Acid Coder

Typescript Zombie. Youtube Pikachu On Acid. (Unrelated to programming but by watching it you become a good developer overnight)