Obtain compile-time error upon assignment through type predicate

36 Views Asked by At

I know how to define a custom type predicate:

type UnsignedInteger = number;

function isUnsigned (s: number): s is UnsignedInteger {
   return s > -1
}

But how can I obtain such an error if I try to assign an invalid number?

const a: UnsignedInteger = -1 // Compiler error: cannot assign...
1

There are 1 best solutions below

0
On

A type predicate does not change the type.

Currently, the functionality you require is not available in Typescript unless if you list out every possible number, like the following:

type Digit = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;