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
{{ message }}
Repository navigation
Always assigning to an un-initialized variable in an exhaustive switch #30000
Search Terms:
switch case exhaustive assignment assign undefined TS2322
Code
Compile with the flags --noImplicitReturns --noImplicitAny --strictNullChecks
enumTest{A,B,C}// this example correctly understands that all possible values of t are handledfunctionfoo(t: Test): number{switch(t){caseTest.A:
return1;caseTest.B:
return2;caseTest.C:
return3;}}// this should be identical to foo, since a is always assigned as the switch is exhaustivefunctionbar(t: Test): number{leta;switch(t){caseTest.A:
a=1;caseTest.B:
a=2;caseTest.C:
a=3;}returna;// I don't expect an error here}
Expected behavior:
Code compiles with no errors. When a is returned in bar, its type is number. Typescript understands that an exhaustive switch with each case assigning to a type-inferred variable means that the variable's type is the union of each assigned value's type. I'd expect this to work because returns within an exhaustive switch are understood in a similar manner.
Actual behavior:
When a is returned in bar, its type is number | undefined
TS2322: Type 'number | undefined' is not assignable to type 'number'.
Type 'undefined' is not assignable to type 'number'.
Playground Link: link here
Turn on noImplicitReturns, noImplicitAny, and strictNullChecks.
functionnoMore(_: never): never{thrownewError('Boom!');}// this should be identical to foo, since a is always assigned as the switch is exhaustivefunctionbar(t: Test): number{leta;switch(t){caseTest.A:
a=1;break;caseTest.B:
a=2;break;caseTest.C:
a=3;break;default: returnnoMore(t);}returna;// <-- works}
Activity
RyanCavanaugh commentedon Apr 1, 2019
Comments in #18362 still apply. We have some special-casing we're capable of doing for
return, but it doesn't generalize to assignments.zpdDG4gta8XKpMCd commentedon Apr 2, 2019
how is it not covered by officially recommended:
?
zpdDG4gta8XKpMCd commentedon Apr 2, 2019
http://www.typescriptlang.org/docs/handbook/advanced-types.html