Skip to content

Commit 37d8875

Browse files
cellogtimdorr
authored andcommitted
Convert applyMiddleware.js to typescript (reduxjs#3529)
* convert applyMiddleware.js to typescript * vastly improve the definition of middleware types
1 parent 5999992 commit 37d8875

File tree

2 files changed

+21
-7
lines changed

2 files changed

+21
-7
lines changed

index.d.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -211,7 +211,7 @@ export function combineReducers<M extends ReducersMapObject<any, any>>(
211211
* dispatched.
212212
*/
213213
export interface Dispatch<A extends Action = AnyAction> {
214-
<T extends A>(action: T): T
214+
<T extends A>(action: T, ...extraArgs: any[]): T
215215
}
216216

217217
/**

src/applyMiddleware.js renamed to src/applyMiddleware.ts

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,13 @@
11
import compose from './compose'
2+
import {
3+
Middleware,
4+
StoreEnhancer,
5+
StoreCreator,
6+
AnyAction,
7+
Reducer,
8+
Dispatch,
9+
MiddlewareAPI
10+
} from '..'
211

312
/**
413
* Creates a store enhancer that applies middleware to the dispatch method
@@ -16,19 +25,24 @@ import compose from './compose'
1625
* @param {...Function} middlewares The middleware chain to be applied.
1726
* @returns {Function} A store enhancer applying the middleware.
1827
*/
19-
export default function applyMiddleware(...middlewares) {
20-
return createStore => (...args) => {
21-
const store = createStore(...args)
22-
let dispatch = () => {
28+
export default function applyMiddleware(
29+
...middlewares: Middleware[]
30+
): StoreEnhancer {
31+
return (createStore: StoreCreator) => <S, A extends AnyAction>(
32+
reducer: Reducer<S, A>,
33+
...args: any[]
34+
) => {
35+
const store = createStore(reducer, ...args)
36+
let dispatch: Dispatch = () => {
2337
throw new Error(
2438
'Dispatching while constructing your middleware is not allowed. ' +
2539
'Other middleware would not be applied to this dispatch.'
2640
)
2741
}
2842

29-
const middlewareAPI = {
43+
const middlewareAPI: MiddlewareAPI = {
3044
getState: store.getState,
31-
dispatch: (...args) => dispatch(...args)
45+
dispatch: (action, ...args) => dispatch(action, ...args)
3246
}
3347
const chain = middlewares.map(middleware => middleware(middlewareAPI))
3448
dispatch = compose(...chain)(store.dispatch)

0 commit comments

Comments
 (0)