skip to Main Content

I define the redux logger "redux-logger": "^3.0.6" in react store.ts like this:

import { configureStore } from '@reduxjs/toolkit';
import rootReducer from '@/redux/reducer/combineReducer';
import { createLogger } from 'redux-logger';
import thunk from 'redux-thunk';
import * as Redux from "redux";
import { Middleware } from 'redux';

const logger: Redux.Middleware = createLogger(); 
const initialState = {};

const store = configureStore({
    reducer: rootReducer,
    middleware: [logger as Middleware, thunk],
    devTools: process.env.NODE_ENV !== 'production',
    preloadedState: initialState
});

export default store;

then compile the project using pnpm run build, shows error like this:

src/redux/store/store.ts:8:7 - error TS2322: Type 'Middleware<{}, any, Dispatch<UnknownAction>>' is not assignable to type 'Middleware<{}, any, Dispatch<AnyAction>>'.
  Type '(next: (action: unknown) => unknown) => (action: unknown) => unknown' is not assignable to type '(next: Dispatch<AnyAction>) => (action: any) => any'.
    Types of parameters 'next' and 'next' are incompatible.
      Types of parameters 'action' and 'action' are incompatible.
        Type 'unknown' is not assignable to type 'AnyAction'.

8 const logger: Redux.Middleware = createLogger();
        ~~~~~~


Found 1 error in src/redux/store/store.ts:8

 ELIFECYCLE  Command failed with exit code 2.

Am I missing something? what should I do to fixed this issue?

2

Answers


  1. You need to explicitly mention the type of the createLogger() Middleware.

    const logger: Redux.Middleware<{}, any, Dispatch<AnyAction>> = createLogger(); 
    
    Login or Signup to reply.
  2. Or use getDefaultMiddleware:

    import { configureStore } from '@reduxjs/toolkit';
    import { createLogger } from 'redux-logger';
    
    const logger = createLogger();
    
    const store = configureStore({
      reducer: () => {},
      middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(logger),
    });
    
    export default store;
    

    package versions:

    "devDependencies": {
      "@types/redux-logger": "^3.0.13",
      "redux-logger": "^3.0.6",
      "typescript": "^5.2.2",
      "vite": "^5.1.1"
    },
    "dependencies": {
      "@reduxjs/toolkit": "^2.2.1"
    }
    

    stackblitz

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search