Typescript issues when adding custom middleware
See original GitHub issueFrom the docs, I can get the type of dispatch
by using typeof store.dispatch
, this works well with the default middlewares. However, when I add my custom middleware, the inferred type of dispatch
becomes Dispatch<AnyAction>
. My question is, how can I properly type the custom middleware to make everything work together?
Here is the code for my store set up:
import { configureStore, getDefaultMiddleware, Action } from '@reduxjs/toolkit';
import { ThunkAction } from 'redux-thunk';
import { createLogger } from 'redux-logger';
import rootReducer, { RootState } from './rootReducer';
const middleware = [...getDefaultMiddleware<RootState>()];
if (process.env.NODE_ENV === 'development') {
middleware.push(createLogger());
}
function configStore(initialState: any) {
const store = configureStore({
reducer: rootReducer,
middleware,
preloadedState: initialState,
});
if (process.env.NODE_ENV === 'development' && module.hot) {
module.hot.accept('./rootReducer', () => {
const newRootReducer = require('./rootReducer').default;
store.replaceReducer(newRootReducer);
});
}
return store;
}
export type AppDispatch = ReturnType<typeof configStore>['dispatch'];
export type AppThunk = ThunkAction<void, RootState, unknown, Action<string>>;
export default configStore;
with this setup, the inferred type of dispatch
is

when I add my custom middleware, I just change
const middleware = [...getDefaultMiddleware<RootState>()];
to
const middleware = [...getDefaultMiddleware<RootState>(), customMiddleware];
then the inferred dispatch becomes
This will cause ts to complain when I dispatch a thunk action
Here is how I define my custom middleware
const customMiddleware: Middleware<{}, RootState> = store => next => action => {
console.log(store.getState());
const res = next(action);
console.log(res);
return res;
};
I have tried the suggestions in the doc but it does not solve the problem. https://redux-toolkit.js.org/usage/usage-with-typescript/#correct-typings-for-the-dispatch-type
Could someone help me?
note: I’m using version 1.2.4
Issue Analytics
- State:
- Created 4 years ago
- Reactions:13
- Comments:10 (3 by maintainers)
In case anyone ends up here from google like I did, my issue was that the middleware I was adding (
LogRocket.reduxMiddleware()
) returned it’s type asany
, which broke thunks as described above.For me, the simplest solution I came up with was to use
as ReturnType<typeof getDefaultMiddleware>
for it (since it’s the rightmost middleware anyway):Cut down example from my code:
If you have to change the order of middlewares, you should annotate the middlewares type manually. For example,