Commit 568a440f authored by Robert Knight's avatar Robert Knight

Prevent confusing error if action payload has a field called `type`

Previously if a payload had a field called `type`, it would override the value
passed in the `type` argument to `makeAction`, causing confusing errors.
parent 31c1555b
...@@ -216,6 +216,9 @@ export function makeAction< ...@@ -216,6 +216,9 @@ export function makeAction<
Reducers extends ReducerMap<any>, Reducers extends ReducerMap<any>,
Type extends keyof Reducers, Type extends keyof Reducers,
>(reducers: Reducers, type: Type, payload: Parameters<Reducers[Type]>[1]) { >(reducers: Reducers, type: Type, payload: Parameters<Reducers[Type]>[1]) {
if (payload && 'type' in payload) {
throw new Error('Payload cannot contain a `type` field');
}
// nb. `reducers` is not used here. It exists purely for type inference. // nb. `reducers` is not used here. It exists purely for type inference.
return { type, ...payload }; return { type, ...payload };
} }
......
/* global process */ /* global process */
import { createStore, createStoreModule } from '../create-store'; import { createStore, createStoreModule, makeAction } from '../create-store';
function initialState(value = 0) { function initialState(value = 0) {
return { count: value }; return { count: value };
...@@ -298,3 +298,19 @@ describe('createStore', () => { ...@@ -298,3 +298,19 @@ describe('createStore', () => {
}); });
} }
}); });
describe('makeAction', () => {
// Dummy reducers map.
const reducers = {};
it('merges type and payload', () => {
const action = makeAction(reducers, 'SET_SEARCH', { query: 'foo' });
assert.deepEqual(action, { type: 'SET_SEARCH', query: 'foo' });
});
it('does not allow payload to contain a `type` field', () => {
assert.throws(() => {
makeAction(reducers, 'SET_SEARCH', { query: 'foo', type: 'bar' });
}, 'Payload cannot contain a `type` field');
});
});
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment