在具有多个操作有效负载类型时,使用 TypeScript 设置 Redux 时出现问题



我正在尝试在反应应用程序中使用打字稿设置 redux,但我不明白我做错了什么。 以下是我的类型和动作创作者。

export type FetchFamilyListError = {
type: typeof FETCH_FAMILY_LIST_ERROR;
payload: string;
};
export type FetchFamilyListSuccess = {
type: typeof FETCH_FAMILY_LIST_SUCCESS;
payload: Family[];
};
export type FamilyActions = FetchFamilyListError | FetchFamilyListSuccess;
export const fetchFamilyListError = (error: string): types.FamilyActions => ({
type: types.FETCH_FAMILY_LIST_ERROR,
payload: error
});
export const fetchFamilyListSuccess = (
families: Family[]
): types.FamilyActions => ({
type: types.FETCH_FAMILY_LIST_SUCCESS,
payload: families
});

这是减速器。

export type familyState = {
families: Family[];
filters: {
size: number;
};
error: string | null;
};
const initialState: familyState = {
families: [],
filters: {
size: 0
},
error: null
};
const familyReducer = (
state = initialState,
action: types.FamilyActions
): familyState => {
const actions = {
[types.FETCH_FAMILY_LIST_ERROR]: () =>
produce(state, draftState => {
draftState.error = action.payload; // <--- error here
}),
[types.FETCH_FAMILY_LIST_SUCCESS]: () => ({
families: [],
filters: {
size: 0
},
error: null
}),
default: () => state
};
return actions[action.type] ? actions[action.type]() : actions.default();
};

我正在收到类型"字符串 |Family[]' 不能分配给类型"字符串 |空'。 类型"家庭[]"不能分配给类型"字符串">我想这是因为 action.payload 可以是字符串或 Family[],我该如何解决这个问题?

现在我正在做这个

draftState.error =
typeof action.payload === "string" ? action.payload : null;

但这似乎不是正确的方法。

我想这是因为action.payload可以是字符串或Family[]

正确,问题出在您的化简器中,action被定义为types.FamilyActions,因此当您尝试设置draftState.error时会出现歧义,因为 TS 无法确定它正在处理哪个操作。

鉴于我们知道它将基于操作类型是哪一个,您可以将有效负载转换为适当的类型,例如

draftState.error = action.payload as string

最新更新