I have a reducer that does different actions depending on the action.type
, actions payload is different for certain actions.
export enum ActionType {
UpdateEntireState = "UPDATE_ENTIRE_STATE",
UpdateStateItem = "UPDATE_STATE_ITEM"
}
type TypeEditData = {
id: string;
name: string;
surname: string;
age: number;
};
export type State = TypeEditData[];
export type Action = UpdateEntireState | UpdateStateItem;
type UpdateEntireState = {
type: ActionType.UpdateEntireState;
payload: State;
};
type UpdateStateItem = {
type: ActionType.UpdateStateItem;
payload: { id: string; data: TypeEditData };
};
export function reducer(state: State, action: Action): State {
const { type, payload } = action;
switch (type) {
case ActionType.UpdateEntireState: {
return [...payload];
}
case ActionType.UpdateStateItem: {
const person = state.filter((item) => item.id === payload.id);
return [...state, ...payload];
}
default: {
throw Error("Wrong type of action!");
}
}
}
This code won’t work, the errors will say that my action payload can be State
or { id: string; data: TypeEditData }
.
However, if I access the payload property inside switch case using dot notation like so
return [...action.payload];
There won’t be any errors and the type guard will work fine.
How const { type, payload } = action;
differs from action.type
and action.payload
in terms of types and why doesn’t typeguard work with spread syntax?
TS version – 4.3.4