'Relative Interface (TYPESCRIPT)

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


Solution 1:[1]

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;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Buszmen