Is it possible to restrict number to a certain range Is it possible to restrict number to a certain range typescript typescript

Is it possible to restrict number to a certain range


If You have small range, you can always write something like:

type MyRange = 5|6|7|8|9|10let myVar:MyRange = 4; // oops, error :)

Of course it works just for integers and is ugly as hell :)


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

Only runtime checks/assertions can achieve that :(


Yes, it's possible BUT:

The 1st. Solution Will be a dirty SolutionThe 2nd. Solution Will be partial (from x to y where y is a small number, 43 in my case)The 3rd. Solution will be a Complete solution but really advance with Transformers, Decorators, etc.

1. Dirty solution ( the easiest and fast way first ) using @Adam-Szmyd solution:

type RangeType = 1 | 2 | 3

if you need an extensive range, just print and copy/paste:

// Easiest just incrementallet range = (max) => Array.from(Array(max).keys()).join(" | ");console.log('Incremental')console.log(range(20))// With range and stepslet rangeS = (( min, max, step) => Array.from( new Array( max > min ? Math.ceil((max - min)/step) : Math.ceil((min - max)/step) ), ( x, i ) => max > min ? i*step + min : min - i*step ).join(" | "));console.log('With range and steps')console.log(rangeS(3,10,2))