-
Notifications
You must be signed in to change notification settings - Fork 12.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add numeric predicate expression literal types #49409
Comments
Related to #26382 and or #15645 I'm not sure how to make sense of the syntax here. It resembles a tagged template literal where I'm not seeing what I'd consider a real-world use case in this suggestion. Ideally there'd be some examples that show why the absence of this feature is a pain point. Like, "It would be nice for the compiler to catch the common mistake where people pass negative or possibly-negative numbers to |
See also #15480 I am also super curious about use cases |
@jcalz :
As for other use cases :
const midnight: Bounded<0,23> = 0; // OK
const invalid: Bounded<0,23> = 25; // Error but also RGB values : type RGB = {
r : Bounded<0,255>
g: Bounded<0,255>
b: Bounded<0,255>
};
const blue : RGB = { r: 0, g: 0, b: 255 };
const invalid: RGB = { r: 0, g: 0, b: 256 }; Ranges are pretty obvious use cases. This proposal is mainly to support this use case, but allow for more like natural numbers or just non floating numbers. Here are other use cases :
In math science, data science, or IA domains, be able to constrain numbers statically as inputs can prevent errors. |
Suggestion
🔍 Search Terms
List of keywords you searched for before creating this issue. Write them down here so that others can find this suggestion more easily and help provide feedback.
number template literal type
template number literal type
expression number literal types
bounded numbers
✅ Viability Checklist
My suggestion meets these guidelines:
⭐ Suggestion
I'd like to see number expression literal types. Like string template literal types but for numbers. But since numbers are computed through expressions, it would be more helpfull to have numbers matching with computation expressions.
📃 Motivating Example
Typescript allows you to define template string literal types like this :
But cannot do the same for real numbers.
What if you could indeed declare numbers with expression literal types :
it would match like this :
The type system would just compute the expression and check that the result should be equal true to match a number.
Only number, bits and logic operators would be allowed inside
n``
:+
-
*
/
%
**
>
<
==
===
<=
>=
||
&&
|
&
^
allowing Math functions could also be doable, but not mandatory.
You could also use it with extend ternary operator :
💻 Use Cases
This could be used to check for non zero positive numbers :
Or bounded numbers to express rand results :
The text was updated successfully, but these errors were encountered: