|
1 | | -import { Middleware, GetState, Dispatch, Reducer, Store } from '../types'; |
| 1 | +import { Middleware, Dispatch, GetState } from '../types'; |
2 | 2 |
|
3 | | -export interface ThunkMiddleware<State, ExtraArgument> |
4 | | - extends Middleware<State, Reducer<State>, Thunk<State, ExtraArgument, any>> { |
5 | | - withExtraArgument: <EA>(extraArgument: EA) => ThunkMiddleware<State, EA>; |
| 3 | +export interface Delegate<S, E, R> { |
| 4 | + (dispatch: Dispatch<S>, getState: GetState<S>, extraArgument: E): R; |
6 | 5 | } |
7 | 6 |
|
8 | | -export interface Delegate<State, ExtraArgument, Return> { |
9 | | - (dispatch: ThunkDispatch<State, ExtraArgument>, getState: GetState<State>, extraArgument: ExtraArgument): Return; |
| 7 | +export interface Thunk<S, E, R> { |
| 8 | + (state: S): Delegate<S, E, R>; |
10 | 9 | } |
11 | 10 |
|
12 | | -export interface ThunkDispatch<State, ExtraArgument> extends Dispatch<Reducer<State>> { |
13 | | - <Return>(reducer: Thunk<State, ExtraArgument, Return>): Return; |
| 11 | +declare module '../types' { |
| 12 | + export interface Dispatch<S> { |
| 13 | + <R, E = any>(thunk: Thunk<S, E, R>): R; |
| 14 | + } |
14 | 15 | } |
15 | 16 |
|
16 | | -export interface Thunk<State, ExtraArgument, Return> { |
17 | | - (state: State): Delegate<State, ExtraArgument, Return>; |
| 17 | +export interface ThunkMiddleware<E> extends Middleware { |
| 18 | + withExtraArgument: <E>(extraArgument: E) => ThunkMiddleware<E>; |
18 | 19 | } |
19 | 20 |
|
20 | | -const thunkFactory = (extraArgument?) => { |
21 | | - const thunk = store => next => reducer => { |
22 | | - if (typeof reducer !== 'function') throw new Error('Thunk requires reducers as functions'); |
23 | | - const state = store.getState(); |
24 | | - const result = reducer(state); |
| 21 | +const thunkFactory = <E>(extraArgument?: E): ThunkMiddleware<E> => { |
| 22 | + const thunk = (store => next => reducer => { |
| 23 | + if (typeof reducer !== 'function') throw new Error('Thunk reducer must return a function'); |
| 24 | + const result = reducer(store.getState()); |
25 | 25 | if (typeof result === 'function') return result(store.dispatch, store.getState, extraArgument); |
26 | | - else { |
27 | | - next(_ => result); |
28 | | - return reducer; |
29 | | - } |
30 | | - }; |
31 | | - thunk['withExtraArgument'] = thunkFactory; |
| 26 | + else return next(_ => result); |
| 27 | + }) as ThunkMiddleware<E>; |
| 28 | + |
| 29 | + thunk.withExtraArgument = thunkFactory; |
| 30 | + |
32 | 31 | return thunk; |
33 | 32 | }; |
34 | 33 |
|
35 | | -export default thunkFactory() as ThunkMiddleware<any, any>; |
| 34 | +export const thunk = thunkFactory(); |
0 commit comments