Typescript: 2.4.1
I am exploring the creation of a helper function to produce redux action creators.
Here is what I have:
interface IAction<T extends string, P = undefined> {
type: T;
payload: P;
}
function createAction<T extends string>(type: T): () => IAction<T, undefined>;
function createAction<T extends string = '', U = undefined, V = {}>(type: T, actionCreator: (payload: U) => V): (payload: U) => IAction<T, V>;
function createAction<T extends string>(type: T, actionCreator?: (payload?: any) => any) {
return (payload: any) => ({
payload,
type,
});
}
enum ActionType {
INCREMENT = 'COUNTER/INCREMENT',
DECREMENT = 'COUNTER/DECREMENT',
ASYNC_INCREMENT = 'COUNTER/ASYNC_INCREMENT',
}
const increment = createAction(ActionType.INCREMENT, () => ({ amount: 1 }));
const incrementBy = createAction(ActionType.INCREMENT, (amount: number) => amount);
In this instance, I anticipate increment
being a function that requires no arguments, and incrementBy
needing exactly one input (a number
).
incrementBy
functions correctly, however, when calling increment()
without any arguments, Typescript generates the following error:
[ts] Expected 1 argument, but received 0;
When attempting to call it in the same way as incrementBy
, for example with increment(42)
, I encounter this error:
[ts] Argument of type '42' is not compatible with parameter of type 'undefined';
For it to work, I need to do this: increment(undefined)
.
Is there a solution to address this issue?