Imagine having a union type structured like this:
type State = {
value: number
things: []
}
type Action =
| {
type: 'INCREMENT'
data: number
}
| {
type: 'DECREMENT'
data: number
}
| {
type: 'DO_THING'
data: {
id: string
name: string
}
}
Now, picture having a reducer function written in this way:
function reducer(state: State, action: Action): State {
switch (action.type) {
case 'INCREMENT':
return increment(state, action)
case 'DECREMENT':
return decrement(state, action)
case 'DO_THING':
return addItem(state, action)
default:
return state
}
}
While defining my action helper functions, an error pops up. For instance:
function increment(state: State, action: action): State {
return {
...state,
number: action.data + 1 // this is the culprit
}
}
The error stems from the union type where data
can be either number
or the specified object. The error message reads:
Type 'number | { id: string; value: string }' is not assignable to type 'number'
I grasp why the error occurs since value
is strictly defined as just number
. But... how can I resolve this issue? What steps should I take to properly type everything for smooth operation?