-
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
Guarded if statements #13426
Comments
I wonder what's the difference between type assertion when guarded if statement is not used along with overloading. In the example, you can simply cast y to Also, what if two nesting guarded if blocks conflict? |
No, it can be used in all parts of the code, not necessarily overload implementations. That's just a use case. If a nested guarded if block conflicts then it would merge the types ( |
Yes, they do, thanks! I couldn't find them when searching. Well, here's another issue that someone can stumble upon instead of making a new one, at least. =P (And another syntax suggestion as well.) |
I tend to write functions that have multiple overloads. The function shouldn't be called using the original, overloaded signature, and is restricted to the overloaded signatures. This already works great. The problem is that some overloads change multiple arguments, and these arguments will be a specific type if the first argument is of that overload signature.
It's okay if that first paragraph doesn't make sense. Here's a simple example.
This won't work, as the base signature doesn't know anything about the types being narrowed when
x
changes. This is still fine, but as this doesn't work, this is where a guarded statement could come in handy.My proposal is guarded if statements. They do not require functions to operate, and directly modify the types of variables in their scope. Here is the same example, but functional, using them.
This specific example could be done using a guard function, but they can be a bit unwieldy to add (an extra function that you have to put somewhere to only use once in the code, sometimes), they can't modify multiple types simultaneously, and you have to give them both the argument you're guarding with and the argument you need to guard the type of.
Language Feature Checklist
Adds an optional clause
: <variable-name> is <type expression>
between) {
in if blocks. Does not work for single-expression if blocks.Adds custom type narrowing to if blocks. Else blocks following an if block are not narrowed. This functionality mirrors the functionality of type guard functions.
Emit should not be impacted by this feature.
This should not be incompatible with any past or future versions of TypeScript or ECMAScript.
The text was updated successfully, but these errors were encountered: