流类型不匹配,函数接受减速器

时间:2018-11-25 14:47:51

标签: redux flowtype

我想创建一个对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,而是一个对象?

1 个答案:

答案 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})

Here it is on Try Flow.