Skip to content

Union discrimination breaks when destructuring parameters #38020

Closed
@tomchambers2

Description

@tomchambers2

TypeScript Version: 3.7.x-dev.201xxxxx

Search Terms: discriminated discrimination union destructured parameters

Code

type Action = | {type: 'add', payload: {toAdd: number}}  | {type: 'remove', payload: {toRemove: number}}

const reducerBroken = (state: number, {type, payload}: Action) => {
    switch (type) {
        case 'add':
            return state + payload.toAdd
        case 'remove':
            return state - payload.toRemove
    }
}


const reducerWorking = (state: number, action: Action) => {
    switch (action.type) {
        case 'add':
            return state + action.payload.toAdd
        case 'remove':
            return state - action.payload.toRemove
    }
}

Expected behavior:
Typescript recognises that the type of the action has been checked and that the action has been refined to a specific one where the payload properties can be safely accessed.

Actual behavior:
Typescript does not refine the type and it errors saying that the action could be any of the payloads specified in the union type.

Playground Link:
https://www.typescriptlang.org/play/?ssl=21&ssc=2&pln=1&pc=1#code/FAFwngDgpgBAggYxASwPYDsYF4YB8YDe40AXDAOQCGAJteQDQwSVgA2qNZRqctZ6AVwC2AIygAnAL6SYeQsShly4qENQA3KAyYt2neagBKqjYpiDRE6cGAIMAZxAwV1AQgkAhcagDWUTDgAFI6UIGYWYuKMRJBQjMxsHNSSZIgoGACU2AB8hMCysvYA7sggCAAWMIEKWQT5BQ0IlPawVLTkJPUN3c5QIALimCFhMADUOok0AHQgPLRd3U0tFCpqmh0LPbIq-YMww7AAtBN61DNGJpoLksA3Nnbojr2u7uIA6qjiPsjoAObYVQO-GEkUYlCQaHQqQhmRyeQaxVKFSq4PS6BmsVqmwKS1aNDonS23R2AyGIFCsHGqMhUwSp3OvGo2NkuJWly0hKJBRJewOMGO1IwtN0SXOxjWUGutyAA

Related Issues:

Metadata

Metadata

Assignees

No one assigned

    Labels

    Fix AvailableA PR has been opened for this issue

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions