首页 > 解决方案 > Redux 和 Typescript 中间件

问题描述

我正在尝试将 Javascript 编写的 React 应用程序转换为 Typescript,但它真的让我很难受。错误消息对我来说真的很难理解。我试图创建一个简单的中间件,但它给出了一个错误,我一直在尝试解决大约 5 个小时。

const loggerMiddleware: Middleware = (api: MiddlewareAPI) => (next: Dispatch<AnyAction>) => (action) => {
    const returnValue = next(action)

    console.log('state after dispatch', api.getState())

    // This will likely be the action itself, unless
    // a middleware further in chain changed it.
    return returnValue

}


export default function configureStore(history: History, initialState?: ApplicationState) {
    const middleware = [
        loggerMiddleware
    ];

    const rootReducer = combineReducers({
        ...reducers,
        router: connectRouter(history)
    });

    const enhancers = [];
    const windowIfDefined = typeof window === 'undefined' ? null : window as any;
    if (windowIfDefined && windowIfDefined.__REDUX_DEVTOOLS_EXTENSION__) {
        enhancers.push(windowIfDefined.__REDUX_DEVTOOLS_EXTENSION__());
    }

    return createStore(
        rootReducer,
        initialState,
        compose(applyMiddleware(...middleware), ...enhancers)
    );
}




Severity    Code    Description Project File    Line    Suppression State   Suppression State
Error   TS2345  (TS) Argument of type '{ loggerMiddleware: Middleware<{}, any, Dispatch<AnyAction>>; }' is not assignable to parameter of type 'Middleware<any, any, any>'.
  Type '{ loggerMiddleware: Middleware<{}, any, Dispatch<AnyAction>>; }' provides no match for the signature '(api: MiddlewareAPI<any, any>): (next: Dispatch<AnyAction>) => (action: any) => any'.

编译器想表达什么?

标签: reactjstypescriptredux

解决方案


看起来您loggerMiddleware正在作为命名导出导出。在代码的底部文件中按名称(将其括在括号中)导入它:

import { loggerMiddleware } from '../where/the/file/is.js';

推荐阅读