I'm attempting to do something that I thought would be simple. I simply want to turn React's reducer function (dispatch below) into a function (dispatcher() below) that accepts the type and payload properties as 2 parameters. However the type checking doesn't work as expected. I get the following error, which I suspect has something to do with the fact that the type and payload parameters of dispatcher() aren't actually connected to each other:
Argument of type '{ type: "select" | "precycle" | "preview"; payload: Project | undefined; }' is not assignable to parameter of type 'CarAction'.
Type '{ type: "select" | "precycle" | "preview"; payload: Project | undefined; }' is not assignable to type '{ type: "preview"; payload: Project | undefined; }'.
Types of property 'type' are incompatible.
Type '"select" | "precycle" | "preview"' is not assignable to type '"preview"'.
Type '"select"' is not assignable to type '"preview"'.ts(2345)
Code:
type CarAction =
| {
type: "select" | "precycle";
payload: Project;
}
| {
type: "preview";
payload: Project | undefined;
};
const [state, dispatch] = useReducer(reducer, initState);
const dispatcher = (type: CarAction["type"], payload: CarAction["payload"]) => {
dispatch({ type, payload });
};