0

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...
Davide Valdo
  • 779
  • 8
  • 21
  • Does this answer your question? [Is it possible to restrict number to a certain range](https://stackoverflow.com/questions/39494689/is-it-possible-to-restrict-number-to-a-certain-range) – Trevor Kropp Apr 15 '21 at 04:15
  • You defined `UnsignedInteger` as `number`, so this is the same as `const a: number = -1;`, which of course gives no error. Typescript has structural types, not nominal types. – kaya3 Apr 15 '21 at 05:59

1 Answers1

0

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;
Trevor Kropp
  • 219
  • 1
  • 7