TypeScript type float from 0 to 1

Viewed 561

With Typescript, is it possible to define a type of a float (number) that's between 0 and 1 inclusively?

If this isn't possible at all, a way to define the type of an integer between 0 and 100 inclusively.

1 Answers

Defining the type of an integer between 0 and 100 is trivial, albeit tedious

type IntBetween0And100 = 0 | 1 | 2 | 3 | 4 | 5 | ...

The same thing for floats, not so easy.

I would approach the problem by making use of smart constructors. The idea is quite simple, you shift the responsibility of ensuring that a value is of the correct type from the type system (which is unable to do it) to the runtime.

A simplified example might look like this.

type Option<T> = null | T // a simplified Option monad
type FloatBetween0And100 = number

const isFloatBetween0And100 = (n: unknown): n is FloatBetween0And100 => typeof n === 'number' && n <= 100 && n >= 0

const makeFloatBetween0And100 = (n: number): Option<FloatBetween0And100> => isFloatBetween0And100(n) ? n : null

The article I linked above goes a lot more in detail about this approach, check it out.

Related