我使用的是@reduxjs/toolkit
,我想创建一个可轻松扩展的函数,该函数可以创建一个带有默认缩减器的切片.我现在拥有的实现可以工作,但不是强类型的.如何创建一个函数,使切片的操作类型不仅包含缺省的减法器,而且还包含传入的减法器?我曾try 使用推理类型,但无法使其起作用.
任何指导都将不胜感激.谢谢.
最小示例:
在common.ts
个文件中(其中逻辑可以在切片之间共享)
export interface StoreState<T> {
data: T
status: 'succeeded' | 'failed' | 'idle'
error: string | null
}
// create a slice given a name and make it possible to extend reducers so they include more than just reset and updateStatus
export const createStoreSlice = <T>(props: {
sliceName: string
defaultState: T
reducers?: SliceCaseReducers<StoreState<T>> // <-- want to infer this in slices/<sliceName>.ts
}) => {
const { sliceName, reducers, defaultState } = props
const initialState: StoreState<T> = {
data: defaultState,
status: 'idle',
error: null,
}
return createSlice({
name: sliceName,
initialState,
reducers: {
...reducers, // <--- want to somehow infer the type of this when exporting slice actions
reset: (state) => {
Object.assign(state, initialState)
},
updateStatus: (state, action) => {
state.status = action.payload
},
},
})
}
In slices/<sliceName>.ts
(带有额外逻辑的特定切片)
export const genericSlice = createStoreSlice({
sliceName: 'someSliceName',
defaultState: { someField: 'some value' },
reducers: {
setSomeField: (state, action) => {
const { payload } = action
state.data.someField = payload
},
},
})
// these actions should be strongly typed from the createStoreSlice function parameters and contain the default reducers (eg. reset, updateStatus) and extra ones specific to the slice (eg. setSomeField)
export const { reset, updateStatus, setSomeField } = genericSlice.actions