NGRX/存储有效负载类型混淆

2024-01-07

我有以下行动:

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) { }
}

这是 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 中的类型将按预期流动

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

NGRX/存储有效负载类型混淆 的相关文章

随机推荐