相对接口(TYPESCRIPT)



如何使ISetOpen中的状态具有ISetOpen的相对模态类型?

示例:

如果ISetOpen.modal=='payModal':ISetOpen.state=IPayModal

如果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;

相关内容

  • 没有找到相关文章