|
|
|
|
|
by 0xb0565e487
1070 days ago
|
|
I'm relatively new to programming and had a question about TypeScript's functionality. Is there any specific reason why TypeScript doesn't allow for the creation of custom and intricate data types? For example, I'm unable to define a number type within a specific range, or a string that adheres to a certain pattern (like a postal code). I'm imagining a language where I could define a custom data type with a regular function. For instance, I could have a method that the compiler would use to verify the validity of what I input, as shown below: function PercentType(value: number) {
if (value > 100 || value < 0) throw new Error(); return true;
}Is the lack of such a feature in TypeScript (or any language) a deliberate design decision to avoid unnecessary complexity, or due to technical constraints such as performance considerations? |
|
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.