Skip to content

Union discrimination breaks when destructuring parameters #38020

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
tomchambers2 opened this issue Apr 17, 2020 · 1 comment · Fixed by #46266
Closed

Union discrimination breaks when destructuring parameters #38020

tomchambers2 opened this issue Apr 17, 2020 · 1 comment · Fixed by #46266
Labels
Fix Available A PR has been opened for this issue

Comments

@tomchambers2
Copy link

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:

@MartinJohns
Copy link
Contributor

Duplicate of #12184.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Fix Available A PR has been opened for this issue
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants