4

我正在尝试使用提供的文档将 redux 项目转换为打字稿:

https://redux.js.org/usage/usage-with-typescript#type-checking-middleware

但是,我在使用自定义中间件时遇到了麻烦。这是对我来说导致错误的最小化和提取代码。

商店.ts:

import { configureStore } from '@reduxjs/toolkit';

import reducer from './customReducer';

import { customMiddleware } from "./customMiddleware";

const store = configureStore({
    reducer: {
        custom: customReducer
    },
    middleware: getDefaultMiddleware => getDefaultMiddleware().prepend(customMiddleware)

})

export type RootState = ReturnType<typeof store.getState>

export default store

customMiddleware.ts:

import { Middleware } from 'redux';
import { RootState } from './store';

export const customMiddleware = (): Middleware<{}, RootState> => {
    return store => next => action => {
        return next(action);
    }
}

这会导致几个错误消息: on const store = configur...

'store' 隐式具有类型'any',因为它没有类型注释并且在其自己的初始化程序中直接或间接引用。

关于 RootState 导出:

类型别名 'RootState' 循环引用自身。

关于 customMiddleware 导出:

'customMiddleware' 隐式具有类型'any',因为它没有类型注释并且在其自己的初始化程序中直接或间接引用。

4

2 回答 2

5

在这种情况下,你将不得不以某种方式打破这个圈子。

这里最简单的方法是

export type RootState = ReturnType<typeof customReducer>

编辑:我认为您的初始代码是 reducer: customReducer

使用给定的代码它将不起作用 - 您需要在创建商店之前拆分该减速器创建:

const rootReducer = combineRecucers({
        custom: customReducer
})

export type RootState = ReturnType<typeof rootReducer>

const store = configureStore({
    reducer: rootReducer,
    middleware: getDefaultMiddleware => getDefaultMiddleware().prepend(customMiddleware)

})
于 2021-07-02T15:53:10.207 回答
0

啊,好的,我想通了。问题在于我如何定义我的 customMiddleware。该文档只是将导出定义为中间件:

export const customMiddleware: Middleware = store => next => action => {
    return next(action);
}

但是我将导出作为返回中间件的函数,因为在我的实际代码中有一些初始化:

export const customMiddleware = (): Middleware => {
    return store => next => action => {
        return next(action);
    }
}

所以我只需要在前置时将它作为一个函数调用:

middleware: getDefaultMiddleware => getDefaultMiddleware().prepend(customMiddleware())

我太傻了……

编辑:也需要使用根减速器类型。

于 2021-07-05T08:26:44.440 回答