Skip to content

Convert applyMiddleware.js to typescript #3529

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Aug 29, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,7 @@ export function combineReducers<M extends ReducersMapObject<any, any>>(
* dispatched.
*/
export interface Dispatch<A extends Action = AnyAction> {
<T extends A>(action: T): T
<T extends A>(action: T, ...extraArgs: any[]): T
}

/**
Expand Down
26 changes: 20 additions & 6 deletions src/applyMiddleware.js → src/applyMiddleware.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,13 @@
import compose from './compose'
import {
Middleware,
StoreEnhancer,
StoreCreator,
AnyAction,
Reducer,
Dispatch,
MiddlewareAPI
} from '..'

/**
* Creates a store enhancer that applies middleware to the dispatch method
Expand All @@ -16,19 +25,24 @@ import compose from './compose'
* @param {...Function} middlewares The middleware chain to be applied.
* @returns {Function} A store enhancer applying the middleware.
*/
export default function applyMiddleware(...middlewares) {
return createStore => (...args) => {
const store = createStore(...args)
let dispatch = () => {
export default function applyMiddleware(
...middlewares: Middleware[]
): StoreEnhancer {
return (createStore: StoreCreator) => <S, A extends AnyAction>(
reducer: Reducer<S, A>,
...args: any[]
) => {
const store = createStore(reducer, ...args)
let dispatch: Dispatch = () => {
throw new Error(
'Dispatching while constructing your middleware is not allowed. ' +
'Other middleware would not be applied to this dispatch.'
)
}

const middlewareAPI = {
const middlewareAPI: MiddlewareAPI = {
getState: store.getState,
dispatch: (...args) => dispatch(...args)
dispatch: (action, ...args) => dispatch(action, ...args)
}
const chain = middlewares.map(middleware => middleware(middlewareAPI))
dispatch = compose(...chain)(store.dispatch)
Expand Down