【问题标题】:flowtype how to get a list of function return valuesflowtype如何获取函数返回值的列表
【发布时间】:2017-09-16 03:02:52
【问题描述】:

我想提取 mapStateToProps 给我的道具,作为组件正在获取的道具列表添加到我的 ownProps 中。这对我来说似乎很常见,将 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 是函数本身,而不是返回值。

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

【问题讨论】:

  • 这个问题不清楚。您是否收到了您未预料到的错误?如果是这样,请提供错误文本和代码 sn-p,以便读者重现错误。
  • 不,我没有收到错误消息。我不知道如何获得我想要的类型。

标签: redux flowtype


【解决方案1】:

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

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'>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-13
    • 2016-06-11
    • 2015-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多