-
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
Narrowing type with boolean algebra #35704
Comments
Nitpick: You need to check the items in the guidelines checklist not come up with your own check list (I would say this feature request probably checks the items in there but you should go trough them to make sure) |
I can't reproduce the issue, either. The following works as I expect: function hmm(result: TApiResponse) {
if (!result.valid) {
alert(result.errorMessage); // works
return;
}
console.log(result.value) // works
} I mean, |
@jcalz I have this error on Visual Studio Code: And it fails:
And very weird... I'm trying to reproduce this same error on playground, but I can't. (also, the typo |
What is your workspace typescript version? (Displays bottom right of VSCode) |
@adekau My TypeScript version is 3.7.2 |
@macabeus it's reproducible on playground when |
@ark120202 Oh, thank you! I didn't know about this config. Very thank you. |
Search Terms
Suggestion
I know that TypeScript doesn't do any boolean algebra, but would be very nice to add support for this, even for simple operators, such as
!
.With that we could write more readable and safer code.
Related:
Use Cases
Let's say that we are typing a response from an API:
So, if we receives a valid response, we have a
value
property, otherwise we'll have anerrorMessage
. We can check if it was successful or not checking the boolean value fromvalid
.So we could do it:
But if we use some lint rule such as
no-boolean-literal-compare
we aren't allow to useresult.valid === false
, but just!result.valid
, and it won't narrow, because TypeScript doesn't do any boolean algebra:Checklist
My suggestion meets these guidelines:
The text was updated successfully, but these errors were encountered: