Redux Toolkit slice action TypeScript and keyof

Viewed 28

I am using React Redux toolkit and keyof to specify that one element of my action payload shall be the key of the type, that my state consists of, so I can update the properties of the state using a redux action.

It says that: Type 'Tunnel[] | PassTable[]' is not assignable to type 'Tunnel[] & PassTable[]'.

Can you give me an explanation what the problem is here? Thank you very much!

type Tunnel = {
  ID: number;
  IP: string;
  Mask: string;
  Gateway: string;
  SPI: string;
  TTL: number;
  DTL: number;
};

type PassTable = {
  ID: number;
  Protocol: string;
  IP: string;
  Mask: string;
};

interface ApiState {
  BasicInformation: BasicInformation;
  Tunnels: Tunnel[];
  PassTable: PassTable[];
}

const initialState = {
  BasicInformation: {
    Version: "",
    State: "-",
    Spi: "-",
    Time: "",
  },
  Tunnels: [],
  PassTable: [],
}

type Values<T> = T[keyof T];

type UpdateTableRow<Table extends Array<PassTable | Tunnel>> = Values<{
  [P in keyof Table[number]]: {
    table: "PassTable" | "Tunnels";
    id: number;
    param: P;
    value: Table[number][P];
  };
}>;

const mutableTableUpdate = <
  Table extends PassTable[] | Tunnel[],
  Id extends keyof Table,
  Param extends keyof Table[Id],
  Value extends Table[Id][Param]
>(
  table: Table,
  id: Id,
  param: Param,
  value: Value
) => {
  table[id][param] = value;
  return table;
};

const apiSlice = createSlice({
  name: "api",
  initialState,
  reducers: {
    setTableParamTest(
      state: ApiState,
      action: PayloadAction<UpdateTableRow<PassTable[] | Tunnel[]>>
    ) {
      const { table, id, param, value } = action.payload;
      state[table] = mutableTableUpdate(state[table], id, param, value);
    },
})
0 Answers
Related