gpt4 book ai didi

reactjs - combineReducers 不推断类型

转载 作者:行者123 更新时间:2023-12-04 14:16:24 26 4
gpt4 key购买 nike

我正在使用 combineReducers在我的 React TypeScript 应用中:

// combinedReducer.ts
import { combineReducers } from 'redux'
import reducer1 from './reducer1'
import reducer2 from './reducer2'

const combinedReducer = combineReducers({
reducer1,
reducer2,
})

export default combinedReducer

我从redux documentation了解到那combineReducers应该根据组合的 reducer 推断它的类型。

然而,对我来说它没有,即使每个组合的 reducer 都有它的返回类型被识别: enter image description here enter image description here enter image description here

( ReturnType<typeof combidedReducer>unknown )

这里有什么问题?

这是我最大程度简化的 reducer :

// reducer1.ts
const initialState: boolean = false

const reducer1 = (state = initialState): boolean => state

export default reducer1
// reducer2.ts
const initialState: boolean = false

const reducer2 = (state = initialState): boolean => state

export default reducer2

最佳答案

我使用 redux 4.0.5 和 typescript 4.0.1 时遇到同样的问题。不得不自己写一个推断器:

type BaseReducerMap<S> = {
[K in keyof S]: (state: S[K], action: any) => S
}

export type InferRootState<ReducerMap extends BaseReducerMap<S>, S = any> = {
[K in keyof ReducerMap]: ReturnType<ReducerMap[K]>
}

然后是你的 reducer 组(在你组合它们之前)

const reducers = {
login: loginReducer,
chatUsers: chatUsersReducer,
};
const combinedReducer = combineReducers(reducers);

export type State = InferRootState<typeof reducers>;

然后 typescript 可以成功推断出我的 State 的类型。我不知道为什么它在这个版本中失败了。

关于reactjs - combineReducers 不推断类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59768923/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com