You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
If you have a switch statement that has multiple cases that fall through, and those case statements are not first, TypeScript will not narrow your types in those statements.
It's a bit confusing to explain, but if you look at the playground link below, hopefully it makes sense. You can see if that you get rid of the first case statement, everything works just fine.
🔎 Search Terms
switch, case
🕗 Version & Regression Information
This is the behavior in every version I tried, and I reviewed the FAQ for entries about switch statements
typeThing=|{type: 'a';onlyA: string;}|{type: 'b'|'B';onlyB: string;};constthing: Thing={}asThing;switch(true){casething.type==='B':
break;casething.type==='b'&&thing.onlyB==='a': // TS error on this linecasething.type==='a'&&thing.onlyA==='b': // and on this linecasething.type==='a'&&thing.onlyA==='c':
break;default:
break;}
🙁 Actual behavior
In the first 2 of the 3 case statements that are grouped together, TS will complain that onlyB and onlyA does not exist on type Thing. If you get rid of the very first case statement in the switch, the errors go away.
🙂 Expected behavior
I would expect this code to work as-is, without the need for the 3 case statements to be listed first in the switch statement.
The text was updated successfully, but these errors were encountered:
The one big difference between those issues and this one (as far as I can tell) is that in my example, the 3 grouped case statements do work if they're the first case statements in the switch:
So this type of narrowing is supported by TS inside of a switch(true) statement, but for some reason the order and grouping of the case statements makes the difference here.
Bug Report
If you have a
switch
statement that has multiplecase
s that fall through, and thosecase
statements are not first, TypeScript will not narrow your types in those statements.It's a bit confusing to explain, but if you look at the playground link below, hopefully it makes sense. You can see if that you get rid of the first
case
statement, everything works just fine.🔎 Search Terms
switch, case
🕗 Version & Regression Information
switch
statements⏯ Playground Link
Playground link with relevant code
💻 Code
🙁 Actual behavior
In the first 2 of the 3 case statements that are grouped together, TS will complain that
onlyB
andonlyA
does not exist on typeThing
. If you get rid of the very firstcase
statement in theswitch
, the errors go away.🙂 Expected behavior
I would expect this code to work as-is, without the need for the 3
case
statements to be listed first in theswitch
statement.The text was updated successfully, but these errors were encountered: