-
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
Type narrowing does not work on boolean variables #55586
Comments
For the record, this doesn't work either, so it's nothing to do with the variable: switch (numOrNull !== null) {
case true:
// possibly null error
console.log(numOrNull < 10)
break
} or this: if (isNum === true) {
// possibly null error
console.log(numOrNull < 10)
} Direct comparison of a type guard result to true/false is not recognized as a narrowing operation. |
Related: #37178 This is probably just a pattern that is not supported. And I honestly see no reason why you'd write code like this. |
Ah I see! Of course, I understand this pattern is very uncommon and there are simple alternatives with if-statements. I just wanted to understand why it did not work - whether the control flow analysis does not support this pattern etc. And upon further digging, I found the exact reason why this is not supported. Thanks for the quick replies @fatcerberus @MartinJohns! |
Unlike #37178, this also doesn't work with if statements? Extracting certain logical expressions into local variables to make a complex if more parsable seems like a reasonable use case.
|
π Search Terms
"type narrowing", "type guards", "switch statement", "switch", "possibly null"
π Version & Regression Information
β― Playground Link
https://www.typescriptlang.org/play?ts=5.2.2#code/PTAEHUFMBsGMHsC2lQBd5oBYoCoE8AHSAZVgCcBLA1UABWgEM8BzM+AVwDsATAGiwoBnUENANQAd0gAjQRVSQAUCEmYKsTKGYUAbpGF4OY0BoadYKdJMoL+gzAzIoz3UNEiPOofEVKVqAHSKymAAmkYI7NCuqGqcANag8ABmIjQUXrFOKBJMggBcISGgoAC0oACCbvCwDKgU8JkY7p7ehCTkVDQS2E6gnPCxGcwmZqDSTgzxxWWVoASMFmgYkAAeRJTInN3ymj4d-jSCeNsMq-wuoPaOltigAKoASgAywhK7SbGQZIIz5VWCFzSeCrZagNYbChbHaxUDcCjJZLfSDbExIAgUdxkUBIursJzCFJtXydajBVDtHHwDAAXlAAG9FCUSpx2IgAPJkAByUWg+X6bOk31AAB8BdBoIoAL7BBCcQQ0ZLU6SOUD8pW0hlM5msjnc3n8gCsvGlwUUcoVDIFep5EtAUtAdI1KrI5salqEPMQjutnNt0FAAEIaXTWRKANzBFQSeBkeLCBjCCGQWAKbjFBGgAAUnrZAEo0fL4O4AtB4Mws40UAAeUAARgADHmzYJ3qgNNnc4gC4zmaNBJYyOxIIU+32VAR4II5NJoHhxQHvmxXWPmRbi5BS+Ws7q-bzQLXG83VyUJh5pjKo2AcM0PGQvIhY85gewaF83GZmOwGMxIPxYNA6iJAwwJ6CIXgAEQAKKrAwiALPoEFJNiEHgA4qAAOTCFykASBBQQqOyXxkO8A78L+RyoI4abjPOTiPjowxYPoKAIIg0IJjwzGSLG0QiAYHDYgsTCsBwPBBCUQA
π» Code
π Actual behavior
numOrNull
ispossibly null
inside the switch statementπ Expected behavior
numOrNull
should be narrowed down to typenumber
and there should not be any errorsAdditional information about the issue
No response
The text was updated successfully, but these errors were encountered: