相关接口 (TYPESCRIPT)

Relative Interface (TYPESCRIPT)

如何在 ISetOpen 中使用相对类型的模态在 ISetOpen 中创建状态?

示例:

if ISetOpen.modal === 'payModal': ISetOpen.state = IPayModal

if ISetOpen.modal === 'deleteModal': ISetOpen.state = IDeleteModal

import { createSlice, PayloadAction } from '@reduxjs/toolkit'

interface IPayModal {
  amount: number
  isOpen: boolean
}

interface IDeleteModal {
  id: number
  isOpen: boolean
}

export interface ModalsState {
  payModal: IPayModal
  deleteModal: IDeleteModal
}

const initialState: ModalsState = {
  payModal: {
    amount: 0,
    isOpen: false
  },
  deleteModal: {
    id: 0,
    isOpen: false
  }
}

interface ISetOpen {
  modal: keyof typeof initialState
  state: IPayModal | IDeleteModal
}

export const modalsSlice = createSlice({
  name: 'modals',
  initialState,
  reducers: {
    setOpen: (state, action: PayloadAction<ISetOpen>) => {
      state[action.payload.modal] = action.payload.state
    }
  }
})

export const { setOpen } = modalsSlice.actions

export default modalsSlice.reducer

我不知道你有多重视这个keyof typeof initialState,尤其是在有第三个或更多选项的情况下。

你可以通过将你的接口转换成联合类型来实现你想要的:

type ISetOpen = {
  modal: 'payModal';
  state: IPayModal;
} | {
  modal: 'deleteModal';
  state: IDeleteModal;
}

你当前的ISetOpen接口中的两个属性都是并集,但是modalstate没有关系。

您想要的是 modalstate 的有效配对的并集。我们可以使用映射类型来做到这一点。对于每个键 ("payModal" | "deleteModal"),我们为每种类型创建一个具有特定 modalstate 的对象。

type ISetOpen = {
  [K in keyof ModalsState]: {
    modal: K;
    state: ModalsState[K]
  }
}[keyof ModalsState]

这解析为

type ISetOpen = {
    modal: "payModal";
    state: IPayModal;
} | {
    modal: "deleteModal";
    state: IDeleteModal;
}

这将确保您的所有操作都使用正确的值进行分派。

不幸的是,它没有解决 reducer 中的问题,因为 state[action.payload.modal] 仍然被评估为联合 state.payModal | state.deleteModal。您可能需要在此处使用类型断言。例如,action.payload.state as IPayModal & IDeleteModal;