Skip to content

Commit 7da57bc

Browse files
fix(store): adjust types to allow a generic reducer (#2996)
Closes #2982
1 parent cdb5bd5 commit 7da57bc

File tree

2 files changed

+24
-6
lines changed

2 files changed

+24
-6
lines changed

modules/store/spec/types/reducer_creator.spec.ts

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import { compilerOptions } from './utils';
44
describe('createReducer()', () => {
55
const expectSnippet = expecter(
66
(code) => `
7-
import {createAction, createReducer, on, props} from '@ngrx/store';
7+
import {createAction, createReducer, on, props, ActionCreator, ActionReducer} from '@ngrx/store';
88
99
${code}
1010
`,
@@ -57,6 +57,23 @@ describe('createReducer()', () => {
5757
);
5858
`).toInfer('reducer', 'ActionReducer<number, Action>');
5959
});
60+
61+
it('should support a generic reducer factory', () => {
62+
expectSnippet(`
63+
const creator = null as unknown as ActionCreator;
64+
65+
export function createGenericReducer<TState extends object>(initialState: TState): ActionReducer<TState> {
66+
const reducer = createReducer(
67+
initialState,
68+
on(creator, (state, action) => {
69+
return state ;
70+
})
71+
);
72+
73+
return reducer;
74+
}
75+
`).toSucceed();
76+
});
6077
});
6178

6279
describe('on()', () => {

modules/store/src/reducer_creator.ts

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,7 @@ export interface ReducerTypes<
2222

2323
// Specialized Reducer that is aware of the Action type it needs to handle
2424
export interface OnReducer<State, Creators extends readonly ActionCreator[]> {
25-
(state: State, action: ActionType<Creators[number]>): State extends object
26-
? { [P in keyof State]: State[P] }
27-
: State;
25+
(state: State, action: ActionType<Creators[number]>): State;
2826
}
2927

3028
/**
@@ -42,11 +40,14 @@ export interface OnReducer<State, Creators extends readonly ActionCreator[]> {
4240
* ```
4341
*/
4442
export function on<State, Creators extends readonly ActionCreator[]>(
45-
...args: [...creators: Creators, reducer: OnReducer<State, Creators>]
43+
...args: [
44+
...creators: Creators,
45+
reducer: OnReducer<State extends infer S ? S : never, Creators>
46+
]
4647
): ReducerTypes<State, Creators> {
4748
// This could be refactored when TS releases the version with this fix:
4849
// https://github.com/microsoft/TypeScript/pull/41544
49-
const reducer = args.pop() as OnReducer<State, Creators>;
50+
const reducer = args.pop() as OnReducer<any, Creators>;
5051
const types = (((args as unknown) as Creators).map(
5152
(creator) => creator.type
5253
) as unknown) as ExtractActionTypes<Creators>;

0 commit comments

Comments
 (0)