我想创建一个对reducer起作用的函数(它的重要性不重要,只是进行一些转换,类似于CombineReducers)。我想为减速器提取state
时遇到问题。
这是用于某些组件的简化的减速器:
type someState = {
foo: number,
};
export const someSimpleReducer = (state: someState) => state;
type StateAbstract = {}; // this doesn't work
// type StateAbstract = any; // this works
,这里是具有抽象状态的抽象转换函数:
declare type SimpleReducer<S> = (state: S) => S;
export const transformReducer = (reducer: SimpleReducer<StateAbstract>) => ({
reducer,
});
transformReducer(someSimpleReducer);
我看到以下流错误:
流程:
transformReducer
中缺少属性someSimpleReducer
,但{{1}中却存在属性reducer
,因此无法调用绑定了{{1}的foo
的{{1}} } [2]在第一个参数中
如果我使用StateAbstract
,那么我看不到任何错误...
我该如何写someState
类型,而不是type StateAbstract = any
,而是一个对象?
答案 0 :(得分:1)
declare type SimpleReducer<S> = (state: S) => S;
声明类型SimpleReducer
,该类型是接受S并返回S的函数。
transformReducer
是接受SimpleReducer<StateAbstract>
的函数,即接受StateAbstract
并返回StateAbstract
的函数。
transformReducer
不必关心reducer函数采用哪种类型并返回。代替使用具体类型,而使用泛型:
export const transformReducer = <S>(reducer: SimpleReducer<S>) => ({reducer})