TypeScript: Get the return type of a function without calling it

Firstly, this might seems like madness… and it kind of is, but there are actually situations where this is a sensible thing to do e.g. when there is a function from another module, that you do not want to call (not yet anyway, you are just typing something else), but it does not expose its return type.

Let’s get down to business. First we make a little function.

function one () {
  return 1;
}

Now we need to do some slightly weird things. First we’re going to assign a variable, but pretending that the value true is actually false. This tricks the compiler into assigning the type of value returned from the function, but will not actually call the function at runtime.

const returnValue = (true as false) || one();

Now we can simply use typeof to access the type that’s returned by the function.

type ReturnType = typeof returnValue; // number

If our function had an explicit return value:

function one(): 1 {
  return 1;
}

And we repeat the steps above, we actually get the exact return value of the function.

const returnValue = (true as false) || one();

type ReturnType = typeof returnValue; // 1