cro*_*sey 5 typescript ngrx angular
我有以下行动:
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;
Run Code Online (Sandbox Code Playgroud)
使用以下基础减速器设置
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;
};
}
Run Code Online (Sandbox Code Playgroud)
但是,如果我引入另一个动作,这样可以正常工作:
export class SelectOHAction implements Action {
type = ActionTypes.MODIFY_SELECTED_OH
constructor(public payload: string) { }
}
Run Code Online (Sandbox Code Playgroud)
请注意,此操作的有效负载只是字符串,只要保存或尝试编译,typescript现在声明:"过滤器不会出现类型字符串| OrderHead []"
现在,如果我进入我的reducer,并添加一个新案例:
case orderhead_imp.ActionTypes.MODIFY_SELECTED_OH: {
return {
orderids: state.orderids,
entities: state.entities,
selectedOhID: action.payload
};
}
Run Code Online (Sandbox Code Playgroud)
映射action.payload时我得到了typescript错误:
抛出TS错误"string | OrderHead []不能分配给类型字符串"
显然,在这两种情况下,有效负载都有不同的数据结构,我是否需要以任何其他方式更改我的代码以确保每个案例都为action.payload选择正确的类型?
更新
因此,如果在我的操作中我将有效负载定义为"任何"而不是"字符串"它似乎编译和工作没有问题,但这似乎非常 hacky(而不是预期的行为)
export class SelectOHAction implements Action {
type = ActionTypes.MODIFY_SELECTED_OH
constructor(public payload: any) { }
}
Run Code Online (Sandbox Code Playgroud)
这是 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[]) { }
}
Run Code Online (Sandbox Code Playgroud)
现在,无论您使用过什么item.ActionTypes.CREATE_OH,都将其替换为item.CREATE_OH. Typescript 2.1 中的类型将按预期流动
| 归档时间: |
|
| 查看次数: |
1136 次 |
| 最近记录: |