Closed
Description
TypeScript Version: 2.8.3
Search Terms:
Variable Union
Code
// A *self-contained* demonstration of the problem follows...
enum Types {
A = "A",
B = "B",
}
type ActionA = {type:Types.A,id:number}
type ActionB = {type:Types.B,code:number}
type Actions = ActionA | ActionB
function returnActionCode(action:Actions){
switch (action.type) {
case Types.A:
return action.id
default:
action.code;
}
}
// assigning a intermediate variable breaks the flow analysis
function returnActionCodeFail(action:Actions){
const type = action.type
switch (type) {
case Types.A:
return action.id // Property 'id' does not exist on type 'Actions'. Property 'id' does not exist on type 'ActionB'.
default:
action.code; // Property 'code' does not exist on type 'Actions'. Property 'code' does not exist on type 'ActionA'.
}
}
Expected behavior:
Both functions should compile as they are equivalent
Actual behavior:
Only the first one is valid, Both are actually equal and should be valid, seems that having an intermediate variable assignment breaks the type inference.
Playground Link:
Playgorund Link
Related Issues:
22093