Closed
Description
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 payload
s specified in the union type.
Related Issues: