获取函数的返回类型 [英] Obtaining the return type of a function

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

问题描述

我具有以下功能:

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

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

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