1 | import { Dispatch } from './types/store'
|
2 | import { ActionCreator, ActionCreatorsMapObject, Action } from './types/actions'
|
3 | import { kindOf } from './utils/kindOf'
|
4 |
|
5 | function bindActionCreator<A extends Action>(
|
6 | actionCreator: ActionCreator<A>,
|
7 | dispatch: Dispatch<A>
|
8 | ) {
|
9 | return function (this: any, ...args: any[]) {
|
10 | return dispatch(actionCreator.apply(this, args))
|
11 | }
|
12 | }
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
31 |
|
32 |
|
33 |
|
34 |
|
35 | export default function bindActionCreators<A, C extends ActionCreator<A>>(
|
36 | actionCreator: C,
|
37 | dispatch: Dispatch
|
38 | ): C
|
39 |
|
40 | export default function bindActionCreators<
|
41 | A extends ActionCreator<any>,
|
42 | B extends ActionCreator<any>
|
43 | >(actionCreator: A, dispatch: Dispatch): B
|
44 |
|
45 | export default function bindActionCreators<
|
46 | A,
|
47 | M extends ActionCreatorsMapObject<A>
|
48 | >(actionCreators: M, dispatch: Dispatch): M
|
49 | export default function bindActionCreators<
|
50 | M extends ActionCreatorsMapObject,
|
51 | N extends ActionCreatorsMapObject
|
52 | >(actionCreators: M, dispatch: Dispatch): N
|
53 |
|
54 | export default function bindActionCreators(
|
55 | actionCreators: ActionCreator<any> | ActionCreatorsMapObject,
|
56 | dispatch: Dispatch
|
57 | ) {
|
58 | if (typeof actionCreators === 'function') {
|
59 | return bindActionCreator(actionCreators, dispatch)
|
60 | }
|
61 |
|
62 | if (typeof actionCreators !== 'object' || actionCreators === null) {
|
63 | throw new Error(
|
64 | `bindActionCreators expected an object or a function, but instead received: '${kindOf(
|
65 | actionCreators
|
66 | )}'. ` +
|
67 | `Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?`
|
68 | )
|
69 | }
|
70 |
|
71 | const boundActionCreators: ActionCreatorsMapObject = {}
|
72 | for (const key in actionCreators) {
|
73 | const actionCreator = actionCreators[key]
|
74 | if (typeof actionCreator === 'function') {
|
75 | boundActionCreators[key] = bindActionCreator(actionCreator, dispatch)
|
76 | }
|
77 | }
|
78 | return boundActionCreators
|
79 | }
|