如何在 redux typescript 中获取 payload 类型

How to get the payload type in redux typescript

我在 redux 商店中使用 react typescript。我有两种来自有效载荷的对象类型。我想识别负载对象类型,以便我可以根据类型执行一些操作。

这些是类型

type Car = {
  carID: number,
  color: string,
  model: string,
  score: number
}

type Bus = {
  busID: number,
  model: string,
  type: string
}

type Transports = {
    [id: number]: Array<Car | Bus>;
}

interface State  {
  data: Transports
}

在 reducer 中,我有一个 delete 方法,在该方法中出现错误: Types of parameters 'x' and 'value' are incompatible. Type 'Car | Bus' is not assignable to type 'Car'. 在 forEach 循环中

deleteVehicle: (state: State, action: PayloadAction<Car | Bus>) => {
      if("carID" in action.payload){
        const { id, carID } = action.payload;
        let vehicles = { ...state.data };
        vehicles[id].forEach((x: Car) => {
         if (x.carID === carID) x.score = 0;
       });
      state.data = { ...vehicles };
    }
}

它检查双方,在类型 Car 中可用,但在 Bus

中不可用

解决方案 1:设置一个条件(如果类型是总线,它调用 x.busID 而不是 x.carID)。

解决方案 2:更改两种类型以获得通用 ID

您可以检查键是否存在,以便 Typescript 推断出正确的类型。这称为类型保护。

deleteVehicle: (state: State, action: PayloadAction<Car | Bus>) => {
  const { id, carID } = action.payload;

  const vehicles = state.data;
  
  return {
    ...vehicles,
    vehicles[id]: vehicles[id].map((vehicule) => {
      if ('carId' in vehicule && vehicule.carId === carId) {
        // vehicule will be of type Car
        vehicule.score = 0;
      }

      return vehicule;
    }
  }