HiveBrain v1.2.0
Get Started
← Back to all entries
patterntypescriptCritical

Obtaining the return type of a function

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
returnfunctiontheobtainingtype

Problem

I have the following function:

function test(): number {
    return 42;
}


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

type t = typeof test;


Here, t will be () => number.

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

Solution

EDIT

As of TypeScript 2.8 this is officially possible with ReturnType.
type T10 = ReturnType string>; // string
type T11 = ReturnType void>; // void
type T12 = ReturnType() => T)>; // {}
type T13 = ReturnType() => T)>; // number[]


See this pull request to Microsoft/TypeScript for details.

TypeScript is awesome!

Old-school hack

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();


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.

Context

Stack Overflow Q#36015691, score: 486

Revisions (0)

No revisions yet.