-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Store the result of a type guard into a const but keep its type guard nature. #35603
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
Comments
...and many, many others. Not even joking--this comes up at least once every few weeks. It would be nice to have, but it's a much bigger can of worms than it looks like because tsc would have to track dependencies between different variables in different scopes as opposed to simply considering each variable independently like it can today. |
Sorry for the duplicate. I can understand that it might get complex if $elem is reassigned in my examples. It really isn't worth killing the performance of the compiler for. It just seemed like it should work :) |
It’s not even about whether |
This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes. |
Search Terms
type guard store result const
Suggestion
Store the result of a type guard into a const but keep its "type guardiness".
Use Cases
Suppose I have some code containing a type guard:
Here Typescript knows the
$elem
is not a string, so it must be a JQuery element, and the compiler is happy.But say I want to store the result into a const (perhaps for readability and re-use of the expression)
Is such a thing possible without writing a type guard function? It seems like it could be possible if the result of
(typeof $elem === 'string')
is not boolean, but instead is of type$elem is string
type guard (but is simply emitted as a JavaScript boolean)Checklist
My suggestion meets these guidelines:
The text was updated successfully, but these errors were encountered: