如何在流中获取函数的返回类型? [英] How to get a function's return type in flow?

查看:50
本文介绍了如何在流中获取函数的返回类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此示例中:

const myObj = {
    test: true,
};

type MyType = typeof myObj;

const getValue = (): MyType => {
    return myObj;
};

// how to do this??
type TheReturnType = getValue;

const nextObj: TheReturnType = {
    test: false,
};

我想提取函数将返回的type,所以我可以重用该类型.我想不出办法.上面的方法不起作用. typeof getValue将返回该函数.

I'd like to extract the type that the function will return, so I can reuse that type. I can think of no way to get it. The above doesn't work. typeof getValue will return the function.

推荐答案

这里是ExtractReturn助手,它可以获取函数的返回类型:

Here is an ExtractReturn helper, which can grab the return type of a function:

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

让我们使用这个:

type TheReturnType = ExtractReturn<typeof getValue>

现在TheReturnType将具有getValue函数的返回类型.还要注意,调用ExtractReturn助手需要在函数名称之前使用typeof运算符.

Now TheReturnType will have the return type of the getValue function. Also notice that calling the ExtractReturn helper requires a typeof operator before the function name.

以下是实现ExtractReturn助手的完全不同的方法:

Here is a completely different way to implement the ExtractReturn helper:

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

此帮助程序的工作原理与上面的完全相同;关键是要实现这一目标的方法不止一种.

This helper works exactly the same as the one above; the point is that there is more than one way to accomplish this.

这篇关于如何在流中获取函数的返回类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆