redux-toolkit icon indicating copy to clipboard operation
redux-toolkit copied to clipboard

Enhance PrepareAction type with optional input type

Open clncln1 opened this issue 6 years ago • 3 comments

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

clncln1 avatar Jul 10 '20 06:07 clncln1

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
*/

phryneas avatar Jul 10 '20 06:07 phryneas

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!

clncln1 avatar Jul 10 '20 07:07 clncln1

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 },
	})
);

cadbox1 avatar Jun 12 '23 07:06 cadbox1