Enhance PrepareAction type with optional input type
I am using prepared actions quite often and it would be great to have the possibility to define an optional input type instead of the generic ...args: any[].
So maybe extending the type to something like: type PrepareAction<P, I = void> where I is the only parameter to the function or in case it's not defined, we stick to the generic approach.
Let me know what you think about that
The input type for prepared actions is automatically inferred by the input arguments for the prepare function. You should probably not try to type this by hand any further.
const test = createAction("test", (n: number, s: string) => ({payload: {n,s}}))
/* results in
const test: ActionCreatorWithPreparedPayload<[number, string], {
n: number;
s: string;
}, "test", never, never>
which is a function with a `(n: number, s: string) => ...` signature
*/
Ah, thanks for the help.
I figured out where I messed up. I manually specified the types for createAction (e.g. createAction<PrepareAction<MyPayload>>) and that somehow interfered with the inference.
Just omitting the types works like a charm! Thanks!
if you want to be explicit, you can type the arrow function.
type ActionWithPayload<T> = { payload: T };
type MyActionArguments = { input: string };
type MyActionPayload = { output: string };
const myAction = createAction(
"MY_ACTION",
({ input }: MyActionArguments): ActionWithPayload<MyActionPayload> => ({
payload: { output: input },
})
);