我有以下行动:
export const ActionTypes = {
CREATE_OH: type('[ORDERHEAD] Create Orderhead'),
MODIFY_SELECTED_OH: type('[ORDERHEAD] Select Orderhead'),
};
export class CreateOHAction implements Action {
type = ActionTypes.CREATE_OH
constructor(public payload: OrderHead[]) { }
}
export type Actions
= CreateOHAction
| SelectOHAction;
使用以下基础减速器设置
export interface State {
orderids: string[];
entities: { [orderID: string]: OrderHead };
selectedOhID: string | null;
};
// Set initial state to empty
const initialState: State = {
orderids : [],
entities: {},
selectedOhID: null,
};
export function OHreducer(state = initialState, action: orderhead_imp.Actions): State{
switch(action.type){
case orderhead_imp.ActionTypes.CREATE_OH:
let orders = action.payload;
let newOrders = orders.filter(orderhead => !state.entities[orderhead.orderID]);
let newOrderIds = newOrders.map(orderhead => orderhead.orderID);
let newOrderHeadEntities = newOrders.reduce((entities: { [orderID: string]: OrderHead }, orderhead: OrderHead) => {
return Object.assign(entities, {
[orderhead.orderID]: orderhead
});
}, {});
return {
orderids: [ ...state.orderids, ...newOrderIds ],
entities: Object.assign({}, state.entities, newOrderHeadEntities),
selectedOhID: state.selectedOhID
};
default:
return state;
};
}
但是,如果我引入另一个操作,这效果很好:
export class SelectOHAction implements Action {
type = ActionTypes.MODIFY_SELECTED_OH
constructor(public payload: string) { }
}
注意,有效负载仅针对此操作是字符串,一旦保存或尝试编译,打字稿现在会显示:“字符串类型|OrderHead[]上不存在过滤器”
现在,如果我进入我的减速器,并添加一个新案例:
case orderhead_imp.ActionTypes.MODIFY_SELECTED_OH: {
return {
orderids: state.orderids,
entities: state.entities,
selectedOhID: action.payload
};
}
映射 action.payload 时出现打字稿错误:
抛出 TS 错误“字符串|OrderHead[] 不可分配给字符串类型”
显然,在这两种情况下,有效负载都有不同的数据结构,我是否需要以其他方式更改代码以确保每种情况都为 action.payload 选择正确的类型?
Update
因此,如果在我的操作中我将有效负载定义为“任何”而不是“字符串”,它似乎可以毫无问题地编译和工作,但这似乎veryhacky(而不是预期的行为)
export class SelectOHAction implements Action {
type = ActionTypes.MODIFY_SELECTED_OH
constructor(public payload: any) { }
}