在此示例中:
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.
更多推荐
如何在流中获取函数的返回类型?
发布评论