I'm trying to create a reducer in RTK that takes two arguments which share a generic type. However it seems impossible to share the generic type between the reducer
and prepare
functions.
Here is an example of what I'm trying to achieve
type SetPayload<T> = {
thingToBeSet: MyClass<T>;
value: T;
}
export const mySlice = createSlice({
name: 'mySlice',
initialState,
reducers: {
myReducer: {
reducer: (state, action: PayloadAction<SetPayload<any>>) => {
// Modify state here
},
prepare: <T>(thingToBeSet: MyClass<T>, value: T) => {
return {
payload: { thingToBeSet, value }
}
}
}
}
});
As shown in the code above, my prepare
function uses a generic parameter (as the type of some properties on thingToBeSet must match the type of value). However, this type parameter cannot be used for the type of action
in the reducer function - I tried setting this to any
which gives this error:
The types of 'payload.thingToBeSet' are incompatible between these types.
Type 'MyClass<never>' is not assignable to type 'MyClass<any>'.
Type 'any' is not assignable to type 'never'
As any
cannot be converted to T
- But how can I share T
between both the reducer and prepare functions here?
What I think I want is to somehow create a generic object literal for the myReducer object, something like this (unfortunately not valid TS - is this possible?):
myReducer: <T> {
reducer: (state, action: PayloadAction<SetPayload<T>>) => {
// Modify state here
},
prepare: (thingToBeSet: MyClass<T>, value: T) => {
return {
payload: { thingToBeSet, value }
}
}
}
Any help will be greatly appreciated.