diff --git a/README.md b/README.md index 87f0378..020bdec 100644 --- a/README.md +++ b/README.md @@ -111,18 +111,18 @@ The action creator function will be typed to take whatever you provide as a payload type. If your action creator needs to take arguments other than whatever your payload -is typed as you can provide types in the generic signature: +is typed as you can simply provide a typed payload creator function: ```ts -// a, b, and c are inferred below: -const addThreeNumbers = createAction('ADD_THREE_NUMBERS', (a, b, c) => a + b + c); +// addThreeNumbers accepts three ordinal number aguments and has a number payload: +const addThreeNumbers = createAction('ADD_THREE_NUMBERS', (a: number, b: number, c: number) => a + b + c); ``` If you need to customize the [SFP] `meta` property you can supply a second meta -customizer function: +creator function: ```ts -const addThreeNumbers = createAction( +const addThreeNumbers = createAction( 'ADD_THREE_NUMBERS', // Create `payload` (a, b, c) => a + b + c, @@ -131,6 +131,11 @@ const addThreeNumbers = createAction( ); ``` +Note that the payload and meta creators must accept the same arguments, but can +return different types. In the example above the payload creator takes three +numbers and returns a number while the meta creator takes three numbers and +returns a string. + ### `handleAction(actionCreator, (state: Draft, payload) => void, initialState?: State)` The `handleAction` function returns a single reducer function. The first diff --git a/src/create-action.test.ts b/src/create-action.test.ts index e86f956..9915854 100644 --- a/src/create-action.test.ts +++ b/src/create-action.test.ts @@ -63,6 +63,31 @@ test('meta customizer', () => { }); }); +test('generic inference', () => { + const ac = createAction('generic-inference', (a: number, b: number, c: number) => a + b + c); + expect(ac.type).toBe('generic-inference'); + expect(ac(1, 2, 3)).toEqual({ + type: 'generic-inference', + payload: 6, + }); +}); + +test('generic inference with meta', () => { + const ac = createAction( + 'generic-inference-with-meta', + // Create `payload` + (a, b, c) => a + b + c, + // Create `meta` + (a, b, c) => `${a} + ${b} + ${c}`, + ); + expect(ac.type).toBe('generic-inference-with-meta'); + expect(ac(1, 2, 3)).toEqual({ + type: 'generic-inference-with-meta', + payload: 6, + meta: '1 + 2 + 3', + }); +}); + test('error payload', () => { const ac = createAction('with-error'); expect(ac.type).toBe('with-error');