Home > Back-end >  Relative Interface (TYPESCRIPT)
Relative Interface (TYPESCRIPT)

Time:02-06

How can I make the state in ISetOpen with relative type of modal in ISetOpen?

Example:

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

CodePudding user response:

Is the underlying requirement to track which modal is open?

Don

CodePudding user response:

I don't know how much are you attached to this keyof typeof initialState, especially in a case when there will be 3rd or more options there.

You can achieve what you want by converting your interface into union type:

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