获取函数的返回类型

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

我具有以下功能:

function test(): number { return 42; }

我可以通过使用typeof获得函数的类型:

I can obtain the type of the function by using typeof:

type t = typeof test;

在这里,t将是() => number.

是否可以获取函数的返回类型?我希望t成为number而不是() => number.

Is there a way to obtain the return type of the function? I would like t to be number instead of () => number.

推荐答案

编辑

从TypeScript 2.8开始,ReturnType<T>正式可以做到这一点.

As of TypeScript 2.8 this is officially possible with ReturnType<T>.

type T10 = ReturnType<() => string>; // string type T11 = ReturnType<(s: string) => void>; // void type T12 = ReturnType<(<T>() => T)>; // {} type T13 = ReturnType<(<T extends U, U extends number[]>() => T)>; // number[]

有关详细信息,请参见此处.

See here for details.

TypeScript很棒!

TypeScript is awesome!

老派骇客

不幸的是,瑞安的答案不再起作用.但是我用一个骇客修改了它,对此我感到很不高兴.看哪:

Ryan's answer doesn't work anymore, unfortunately. But I have modified it with a hack which I am unreasonably happy about. Behold:

const fnReturnType = (false as true) && fn();

通过将false转换为true的字面值来工作,以便类型系统认为返回值是函数的类型,但是当您实际运行代码时,它将在false上短路.

It works by casting false to the literal value of true, so that the type system thinks the return value is the type of the function, but when you actually run the code, it short circuits on false.

TypeScript是最好的. :D

TypeScript is the best. :D

更多推荐

获取函数的返回类型

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

发布评论

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

>www.elefans.com

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