Skip to content

Commit 43d1d9d

Browse files
committed
fix(store): fix typing of on fn
1 parent e36dd94 commit 43d1d9d

File tree

2 files changed

+39
-8
lines changed

2 files changed

+39
-8
lines changed

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

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,5 +90,39 @@ describe('createReducer()', () => {
9090
on(foo, (state, action) => { const bar: string = action.bar; return state; });
9191
`).toFail(/'bar' does not exist on type/);
9292
});
93+
94+
it('should infer the typed based on state and actions type with action used in on function', () => {
95+
expectSnippet(`
96+
interface State { name: string };
97+
const foo = createAction('FOO', props<{ foo: string }>());
98+
const onFn = on(foo, (state: State, action) => ({ name: action.foo }));
99+
`).toInfer(
100+
'onFn',
101+
`
102+
ReducerTypes<{
103+
name: string;
104+
}, [ActionCreator<"FOO", (props: {
105+
foo: string;
106+
}) => {
107+
foo: string;
108+
} & TypedAction<"FOO">>]>
109+
`
110+
);
111+
});
112+
113+
it('should infer the typed based on state and actions type without action', () => {
114+
expectSnippet(`
115+
interface State { name: string };
116+
const foo = createAction('FOO');
117+
const onFn = on(foo, (state: State) => ({ name: 'some value' }));
118+
`).toInfer(
119+
'onFn',
120+
`
121+
ReducerTypes<{
122+
name: string;
123+
}, [ActionCreator<"FOO", () => TypedAction<"FOO">>]>
124+
`
125+
);
126+
});
93127
});
94128
});

modules/store/src/reducer_creator.ts

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -40,15 +40,12 @@ export interface OnReducer<State, Creators extends readonly ActionCreator[]> {
4040
* ```
4141
*/
4242
export function on<State, Creators extends readonly ActionCreator[]>(
43-
...args: [
44-
...creators: Creators,
45-
reducer: OnReducer<State extends infer S ? S : never, Creators>
46-
]
43+
...args: [...creators: Creators, reducer: OnReducer<State, Creators>]
4744
): ReducerTypes<State, Creators> {
48-
// This could be refactored when TS releases the version with this fix:
49-
// https://github.com/microsoft/TypeScript/pull/41544
50-
const reducer = args.pop() as OnReducer<any, Creators>;
51-
const types = (args as unknown as Creators).map(
45+
const creators = args.slice(0, -1) as unknown as Creators;
46+
const reducer = args[args.length - 1] as OnReducer<State, Creators>;
47+
48+
const types = creators.map(
5249
(creator) => creator.type
5350
) as unknown as ExtractActionTypes<Creators>;
5451
return { reducer, types };

0 commit comments

Comments
 (0)