flowtype如何获取函数返回值列表

时间:2017-06-16 08:05:00

标签: redux flowtype

我想提取道具mapStateToProps给我,添加到我自己的作为组件获得的道具列表。对于我来说这似乎很常见,使用react / redux和flow。

我可以手动定义我的类型:

type StateProps = {
    activeDuration: ?number,
    activeColor: ?number,
    activeAccessories: ?number[],
}

const mapStateToProps = (state): StateProps => ({
    activeDuration: getActiveDuration(state),
    activeColor: getActiveColor(state),
    activeAccessories: getActiveAccessories(state),
});

但是所有这些getX函数已经知道它们的返回类型。所以实际上mapStateToProps已经知道它的返回类型...... 但我不能用:

type Props = { defaultProp: boolean } & mapStateToProps;

因为mapStateToProps是函数本身,而不是返回值。

问题是:如何获得(未设置)函数将返回的类型。

1 个答案:

答案 0 :(得分:0)

以下代码可以从函数类型中提取返回类型:

type _ExtractReturn<B, F: (...args: any[]) => B> = B;
type ExtractReturn<F> = _ExtractReturn<*, F>;

让我们使用它:

const mapStateToProps = (state) => ({
  activeDuration: getActiveDuration(state),
  activeColor: getActiveColor(state),
  activeAccessories: getActiveAccessories(state),
});

type StateProps = ExtractReturn<typeof mapStateToProps>

以下是基于$ObjMap的替代解决方案:

type ExtractReturn<F> =
  $PropertyType<$ObjMap<{ x: F }, <R>(f: () => R) => R>, 'x'>