我想提取道具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
是函数本身,而不是返回值。
问题是:如何获得(未设置)函数将返回的类型。
答案 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'>