typescripttypes

Is it possible to restrict number to a certain range


Since typescript 2.0 RC (or even beta?) it is possible to use number literal types, as in type t = 1 | 2;. Is it possible to restrict a type to a number range, e.g. 0-255, without writing out 256 numbers in the type?

In my case, a library accepts color values for a palette from 0-255, and I'd prefer to only name a few but restrict it to 0-255:

const enum paletteColor {
  someColor = 25,
  someOtherColor = 133
}
declare function libraryFunc(color: paletteColor | 0-255); //would need to use 0|1|2|...

Solution

  • Edit: this is an old answer. TS >= 4.5 now has tools to deal with this, although it may or may not be limited for your use case. For smallish ranges, this answer works:

    type Enumerate<N extends number, Acc extends number[] = []> = Acc['length'] extends N
      ? Acc[number]
      : Enumerate<N, [...Acc, Acc['length']]>
    
    type IntRange<F extends number, T extends number> = Exclude<Enumerate<T>, Enumerate<F>>
    
    type T = IntRange<20, 300>
    

    ---- Old answer ----

    No it's not possible. That kind of precise type constraint is not available in typescript (yet?)

    Only runtime checks/assertions can achieve that :(