diff --git a/index.d.ts b/index.d.ts index ced1559263..986284b11d 100644 --- a/index.d.ts +++ b/index.d.ts @@ -278,6 +278,10 @@ export interface MiddlewareAPI { * logging actions, performing side effects like routing, or turning an * asynchronous API call into a series of synchronous actions. */ +export interface SpecificMiddleware { + (api: MiddlewareAPI): (next: Dispatch) => Dispatch; +} + export interface Middleware { (api: MiddlewareAPI): (next: Dispatch) => Dispatch; } diff --git a/test/typescript/middleware.ts b/test/typescript/middleware.ts index 3ee95a9849..0ce5530f95 100644 --- a/test/typescript/middleware.ts +++ b/test/typescript/middleware.ts @@ -1,5 +1,5 @@ import { - Middleware, MiddlewareAPI, + Middleware, SpecificMiddleware, MiddlewareAPI, applyMiddleware, createStore, Dispatch, Reducer, Action } from "../../index"; @@ -11,7 +11,15 @@ declare module "../../index" { type Thunk = (dispatch: Dispatch, getState: () => S) => O; -const thunkMiddleware: Middleware = +const thunkSpecificMiddleware: SpecificMiddleware = + ({dispatch, getState}: MiddlewareAPI) => + (next: Dispatch) => + (action: A | Thunk): B|Action => + typeof action === 'function' ? + (>action)(dispatch, getState) : + next(action) + +const thunkGenericMiddleware: Middleware = ({dispatch, getState}: MiddlewareAPI) => (next: Dispatch) => (action: A | Thunk): B|Action => @@ -20,7 +28,23 @@ const thunkMiddleware: Middleware = next(action) -const loggerMiddleware: Middleware = +const loggerSpecificMiddleware: SpecificMiddleware = + ({getState}: MiddlewareAPI) => + (next: Dispatch) => + (action: any): any => { + console.log('will dispatch', action) + + // Call the next dispatch method in the middleware chain. + const returnValue = next(action) + + console.log('state after dispatch', getState()) + + // This will likely be the action itself, unless + // a middleware further in chain changed it. + return returnValue + } + +const loggerGenericMiddleware: Middleware = ({getState}: MiddlewareAPI) => (next: Dispatch) => (action: any): any => { @@ -47,7 +71,7 @@ const reducer: Reducer = (state: State, action: Action): State => { const storeWithThunkMiddleware = createStore( reducer, - applyMiddleware(thunkMiddleware) + applyMiddleware(thunkGenericMiddleware) ); storeWithThunkMiddleware.dispatch( @@ -60,5 +84,5 @@ storeWithThunkMiddleware.dispatch( const storeWithMultipleMiddleware = createStore( reducer, - applyMiddleware(loggerMiddleware, thunkMiddleware) + applyMiddleware(loggerGenericMiddleware, thunkGenericMiddleware) )