我有以下行动:
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:
时,我得到了typescript错误引发TS错误"字符串| OrderHead []不能分配给字符串"
显然,在这两种情况下,有效负载都有不同的数据结构,我是否需要以任何其他方式更改我的代码以确保每个案例都为action.payload提取正确的类型?
更新
因此,如果在我的行动中,我将有效负载定义为"任何"而不是"字符串"它似乎编译和工作没有问题,但这似乎非常 hacky(而不是预期的行为)
export class SelectOHAction implements Action {
type = ActionTypes.MODIFY_SELECTED_OH
constructor(public payload: any) { }
}
答案 0 :(得分:0)
这是Typescript> 2.1和ngrx的类型util的问题。
现在使用typescript 2.1及更高版本,您只需将操作定义为
即可export const CREATE_OH: '[ORDERHEAD] Create Orderhead';
export class CreateOHAction implements Action {
type = CREATE_OH
constructor(public payload: OrderHead[]) { }
}
现在,只要您使用item.ActionTypes.CREATE_OH
,请将其替换为item.CREATE_OH
。类型将按预期使用typescript 2.1