Is there a way to represent a non-negative integer in TypeScript so that the compiler would prevent using fractions and negatives?

Trident D'Gao picture Trident D'Gao · Jan 20, 2014 · Viewed 7.1k times · Source

The number is a very loose representation which sometimes is required to be tighten. In my case I wish a variable was only able to take non-negative integers. Is there a way to enforce this constraint in TypeScript?

Answer

C Snover picture C Snover · Jan 20, 2014

No, this is not possible; there is no* uint or similar in JavaScript, so no corresponding type in TypeScript. There is a open feature request for Contracts which would allow you to provide more robust assertions like these, if it is ever implemented.

* Such data types exist in the Typed Array specification, but these are extensions designed primarily for WebGL, not part of the core language.