我是 typescript 新手,在理解错误时遇到问题。我正在尝试使用 @reduxjs/toolkit 的 createSlice
生成的 reducer ,并将其输入具有以下定义的函数中:
// .d.ts file
export default function persistReducer<S, A extends Action = Action>(
config: PersistConfig<S>,
baseReducer: Reducer<S, A>
): Reducer<S & PersistPartial, A>;
// function definition
export default function persistReducer<State: Object, Action: Object>(
config: PersistConfig,
baseReducer: (State, Action) => State
): (State, Action) => State & PersistPartial { /* ... */
返回以下错误:
Argument of type 'Reducer<CoreState, AnyAction>' is not assignable to parameter of type 'Reducer<unknown, AnyAction>'.
Types of parameters 'state' and 'state' are incompatible.
Type 'unknown' is not assignable to type 'CoreState | undefined'.
Type 'unknown' is not assignable to type 'CoreState'.ts(2345)
但是,当我将 reducer 转换为 redux/toolkit 提供的 Reducer
类型时,它会起作用。
// fails
persistReducer( persistConfig, coreReducer )
// succeeds
persistReducer( persistConfig, coreReducer as Reducer)
据我所知,reducer 已经具有该类型,并且我不确定为什么需要在发送该值之前对其进行转换。我缺少什么?任何帮助将不胜感激!
这是我的切片定义
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
export type User = {
id: string,
name: string,
avatar: string,
token: string
}
export type CoreState {
isSignedIn: boolean,
user: User | null
};
const defaultCoreState : CoreState = {
isSignedIn: false,
user: null
};
export const slice = createSlice({
name: 'core',
initialState: defaultCoreState,
reducers: {
setUser: (state: CoreState, action: PayloadAction<User | null>) => {
state.user = action.payload;
state.isSignedIn = action.payload ? true : false;
}
}
});
export const { setUser } = slice.actions;
export default slice.reducer;
编辑:使用combineReducers
创建的reducer会触发相同的错误,并通过相同的解决方法得到缓解。在我看来,persistReducer 函数在推断类型时遇到了困难,即使它从同一库导入了相同的Reducer 类型定义。给出了什么?
最佳答案
感谢 @phryneas 对 Reactiflux 不和谐的慷慨帮助,问题已经解决。
export default function persistReducer<S, A extends Action = Action>
应该变成:
export default function persistReducer<S, A extends AnyAction>
在调试这个过程时,我在梳理的所有定义中多次看到“Action”和“Any”一词,我错过了其中的区别。 AnyAction
是正确的类型。
关于Typescript、ReduxJS 工具包 - createSlice 生成的 reducer 不可分配给类型 'Reducer<unknown, AnyAction>' 的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65606288/