Closed
Description
TypeScript Version: 3.7.0-beta
Search Terms: enum switch
Code
enum Animal {
DOG,
// Add second member to avoid https://github.com/microsoft/TypeScript/issues/23572.
CAT
}
const zoo: { animal: Animal } | undefined = { animal: Animal.DOG }
// OK.
function intermediateVariable(): Animal {
const animal = zoo?.animal ?? Animal.DOG
switch (animal) {
case Animal.DOG: return Animal.DOG
case Animal.CAT: return Animal.CAT
}
}
// Error: Function lacks ending return statement and return type does not include 'undefined'.(2366)
function expression(): Animal {
switch (zoo?.animal ?? Animal.DOG) {
case Animal.DOG: return Animal.DOG
case Animal.CAT: return Animal.CAT
}
}
Expected behavior: Inferred type doesn't depend on intermediate state.
Actual behavior: Inferred type differs when an expression is switched on directly versus when the value is assigned to an untyped intermediate variable and then switched on.