假设我有一个具有以下定义的通用函数:
const createSlice: <
State,
CaseReducers extends SliceCaseReducers<State>,
Name extends string,
Selectors extends SliceSelectors<State>,
ReducerPath extends string = Name,
>(
options: CreateSliceOptions<State, CaseReducers, Name, ReducerPath, Selectors>
) => Slice<State, CaseReducers, Name, ReducerPath, Selectors>
我想创建一个
createSliceWithSideEffects
函数,如下所示:
const createSliceWithSideEffects = (options) => {
const slice = createSlice(options);
doSomeSideEffects(slice);
return slice;
};
但问题是输入该函数。我看到的唯一解决方案是复制粘贴所有
createSlice
通用参数并定义 createSliceWithSideEffects
函数,如下所示:
const createSliceWithSideEffects = <
State,
CaseReducers extends SliceCaseReducers<State>,
Name extends string,
Selectors extends SliceSelectors<State>,
ReducerPath extends string = Name,
>(
options: CreateSliceOptions<State, CaseReducers, Name, ReducerPath, Selectors>
): Slice<State, CaseReducers, Name, ReducerPath, Selectors> => {
const slice = createSlice(options);
doSomeSideEffects(slice);
return slice;
};
这相当麻烦,每次
createSlice
的定义发生变化时都需要更新定义。另一个问题可能是 SliceCaseReducers
和 SliceSelectors
不是由库导出的,您还必须复制这些类型的定义。
有没有一种方法可以在不复制所有参数的情况下做到这一点?所以它可能看起来像这样,同时还保留通用类型:
const createSliceWithSideEffects = modifiedGenericFunction(createSlice, (...params) => {
const slice = createSlice(...params);
doSomeSideEffects(slice);
return slice;
});
这种方法怎么样,对 createSlice 函数的任何更改都会自动反映在 createSliceWithSideAffects 中。
const createSlice: <
State,
CaseReducers extends SliceCaseReducers<State>,
Name extends string,
Selectors extends SliceSelectors<State>,
ReducerPath extends string = Name,
>(
options: CreateSliceOptions<State, CaseReducers, Name, ReducerPath, Selectors>
) => Slice<State, CaseReducers, Name, ReducerPath, Selectors> = /* implementation */;
type CreateSliceFunction = typeof createSlice;
type CreateSliceOptionsType = Parameters<CreateSliceFunction>[0];
type CreateSliceReturnType = ReturnType<CreateSliceFunction>;
const createSliceWithSideEffects = (
options: CreateSliceOptionsType
): CreateSliceReturnType => {
const slice = createSlice(options);
doSomeSideEffects(slice);
return slice;
};
如果有帮助请告诉我。