I’m writing a simple dispatch function that doesn’t explicitly ask for the type
and payload
but just accepts the values as parameters. But I don’t know how to type them properly.
TLDR: How do I type this to expect the appropriate kind and number of arguments?
Sample code:
const initialState = {
alpha: "string",
number: 123,
boolean: false
}
type TAction =
| {type: "setAlpha"; payload: string}
| {type: "setNum"; payload: number}
| {type: "setBool"; payload: boolean}
| {type: "reset"; payload?: never};
const reducer(state: typeof initialState, {type, payload}: TAction){
switch (type){
case "setAlpha":
return {...state, alpha: payload);
case "setNum":
return {...state, number: payload);
case "setBool":
return {...state, boolean: payload);
case "reset":
return initialState;
default:
return state;
}
}
const [state, dispatch] = useReducer(reducer, initialState);
// SEE HERE:
const dispatcher = <T extends TReducerAction, K extends T["type"]>(
type: K,
payload: T["payload"],
) => { dispatch({ type, payload }); }
I want it to work like:
dispatcher("setAlpha", "a")
dispatcher("setNum", 50)
dispatcher("reset") // <---- PROBLEM IS HERE
When invoking dispatcher
with only 1 argument I get an error, which I know is because the payload
parameter is not optional (payload?: T["payload"]
).
How do I type this to expect the appropriate kind and number of arguments?