I've been working on a function that takes a slice factory as an argument and performs some operations on it. However, I'm facing challenges in setting up the types correctly.
Below is a simple example showcasing the issue:
Slice factory:
export default function sliceFactory() {
return createSlice({
name: "addExercise",
initialState: {
query: "",
},
reducers: {
startSearch(state) {
state.query = "";
},
changeQuery(state, action) {
state.query = action.payload;
},
},
});
}
The sliceFactory
function's type appears to be inferred correctly using:
type Test1 = typeof sliceFactory;
==> () => Slice<{
query: string;
}, {
startSearch(state: WritableDraft<{query: string;}>): void;
changeQuery(state: WritableDraft<{query: string;}>,
action: { payload: any; type: string;}): void;
}, "addExercise">
Utility function:
function checkType<
TState,
TCaseReducers extends SliceCaseReducers<TState>,
TName extends string,
TSliceFactory extends () => Slice<TState, TCaseReducers, TName>,
>(sliceFactory: TSliceFactory) {
return sliceFactory;
}
I anticipate being able to pass sliceFactory
into the utility function and have the types inferred accurately
const result = checkType(sliceFactory);
type Test2 = typeof result ==> ideally, the same as before
Instead, what I received was:
type Test2 ==> () => Slice<unknown, SliceCaseReducers<unknown>, string>
Along with the familiar error message:
Argument of type '() => Slice<{ query: string; }, { startSearch(state: WritableDraft<{ query: string; }>): void; changeQuery(state: WritableDraft<{ query: string; }>, action: { payload: any; type: string; }): void; }, "addExercise">'
is not assignable to parameter of type '() => Slice<unknown, SliceCaseReducers<unknown>, string>'.
What am I overlooking? Appreciate your help!