我是打字稿的新手,在理解错误时遇到了问题。我正在尝试使用由 @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
类型定义,它也无法推断类型。什么给?
答案 0 :(得分:1)
感谢@phryneas 对 Reactiflux discord 的慷慨帮助,问题已得到解决。
export default function persistReducer<S, A extends Action = Action>
应该变成:
export default function persistReducer<S, A extends AnyAction>
在调试时梳理的所有定义中多次看到“Action”和“Any”这个词,我错过了区别。 AnyAction
是正确的类型。