DEV Community

Acid Coder
Acid Coder

Posted on • Updated on

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
Enter fullscreen mode Exit fullscreen mode

it is doable but 0 fun

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>
Enter fullscreen mode Exit fullscreen mode

Typescript Numeric Range Type


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.

Top comments (4)

qishenliang profile image

I have a better suggestion.

type NumericRange<
    START extends number,
    END extends number,
    ARR extends unknown[] = [],
    ACC extends number = never
> = ARR['length'] extends END
    ? ACC | START | END
    : NumericRange<START, END, [...ARR, 1], ARR[START] extends undefined ? ACC : ACC | ARR['length']>
Enter fullscreen mode Exit fullscreen mode
bwca profile image
Volodymyr Yepishev • Edited

I think once I understand how it works, I will transcend to a new plane of existance :D

P.S. Oh, you sly! That's amazing! You've got a new follower :D

canbax profile image

all these "type" orgasm seems to me over-engineering. I like typescript and tried to do similar things for date strings. At the end, just creating a validity check function and using number type seems more reasonable

tylim88 profile image
Acid Coder • Edited

the problem with number is it is too generic

some people have stricter requirement, for example, certain range of numbers, odd number only or non-zero number

for example program crash if the input is 0,

with comprehensive typing, it is possible to prevent the crash the moment we type in the code, we don't need to wait until the runtime

of course type still cant do much with dynamic runtime value, but still it is good to bring down the number

at the end it really depends on how strict and how maintainable your want your code to be in the future

this is especially true if you develop tool for other developers(eg: type safe for database), developer that face end users only likely don't need skill like this