如何在流中获取函数的返回类型? [英] How to get a function's return type in flow?
问题描述
在此示例中:
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屋!