Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

TypeScript actually does have some support for the kinds of types you're suggesting. For example, a US postal code can be defined like so:

    type PostalCode = `${Digit}${Digit}${Digit}${Digit}${Digit}`;

    type Digit = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9';
You could trivially define a `parsePostalCode` function that accepts a string and yields a PostalCode (or throws an error if it's the wrong format).

Ranges like percent are much trickier—TypeScript would need to compute the return type of `Percent + Percent` (0 <= T <= 200), `Percent / Percent` (indeterminate because of division by zero or near-zero values), and so on for all the main operators. In the best case scenario this computation is very expensive and complicates the compiler, but in the worst case there's no clear correct answer for all use cases (should we just return `number` for percent division or should we return `[0, Infinity]`?).

In most mainstream programming languages the solution to this problem is to define a class that enforces the invariants that you care about—Percent would be a class that defines only the operators you need (do you really need to divide Percent by Percent?) and that throws an exception if it's constructed with an invalid value.



Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: