我有以下操作:
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;
使用以下基本 reducer 设置
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) { }
}
注意,有效负载仅用于此操作是字符串,一旦保存或尝试编译, typescript 现在声明:“过滤器不存在于类型字符串|OrderHead[ ]”
现在,如果我进入我的 reducer ,并添加一个新案例:
case orderhead_imp.ActionTypes.MODIFY_SELECTED_OH: {
return {
orderids: state.orderids,
entities: state.entities,
selectedOhID: action.payload
};
}
我在映射 action.payload 时收到 typescript 错误:
抛出 TS 错误 “string|OrderHead[] is not assignable to type string”
显然,在这两种情况下,有效负载具有不同的数据结构,我是否需要以任何其他方式更改我的代码以确保每种情况都为 action.payload 选择正确的类型?
更新
因此,如果在我的操作中我将有效负载定义为“任何”而不是“字符串”,它似乎可以毫无问题地编译和工作,但这似乎非常 hacky(而不是预期的行为)
export class SelectOHAction implements Action {
type = ActionTypes.MODIFY_SELECTED_OH
constructor(public payload: any) { }
}
最佳答案
这是 Typescript >2.1 和 ngrx 的类型实用程序的问题。
现在使用 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 流动
关于angular - NGRX/Store 负载类型混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41956607/