如何在流中获取函数的返回类型?

编程入门 行业动态 更新时间:2024-10-25 08:21:36
本文介绍了如何在流中获取函数的返回类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在此示例中:

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.

更多推荐

如何在流中获取函数的返回类型?

本文发布于:2023-07-22 10:35:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1186749.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   类型   如何在

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!