Skip to content

Intermediate Variable assigment break inference #24376

@rulonder

Description

@rulonder

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions