Narrowing types by `typeof` inside `switch (true)` does not work
See original GitHub issueTypeScript Version: 3.8.3 Nightly
Search Terms:
- switch statement
- switch (true)
Code
let x: string | undefined;
if (typeof x !== 'undefined') {
x.trim(); // works as expected
}
switch (true) {
case typeof x !== 'undefined':
x.trim(); // thinks x is potentially undefined
}
Expected behavior:
Narrowing types should work inside the case
.
Actual behavior:
Any assertion in case
seems to be disregarded
Related Issues:
Issue Analytics
- State:
- Created 4 years ago
- Reactions:32
- Comments:17 (6 by maintainers)
Top Results From Across the Web
TypeScript 3.8.3 not narrowing union type in switch statement
I notice that from TS 4.3.5 and on, the type is narrowed the way I'd expect (the error disappears), but I can't change...
Read more >Documentation - Narrowing - TypeScript
If we'd assigned a boolean to x , we'd have seen an error since that wasn't part of the declared type. x =...
Read more >Narrowing Types in TypeScript - Formidable Labs
Type narrowing is just what it sounds like—narrowing down a general type into something more precise. Here's how to do it.
Read more >Type-Safe TypeScript with Type Narrowing - Rainer Hahnekamp
The type of input in calcAge can be of three different types. ... Strictly speaking function is not a real type, it is...
Read more >Type guards and assertion functions • Tackling TypeScript
Inside the body of getScore() , we don't know if the type of value number or string . ... Narrowing also works if...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
Two come to mind: • readability for big amounts of cases • being able to use fall-throughs for overlapping cases
Having said that I understand it is an edge case. I came across this pattern in a bigger codebase and wanted to make a change. That’s when I noticed that the types are not narrowed in each case.
I have similar usecase:
And I am using this syntax in javascript because it looks better than chain of if else. Sadly can not use in typescript