Skip to main content

What does ReturnType<T> do?

What does ReturnType<T> do?

ReturnType<T> is a built-in TypeScript utility type that returns the result type of function T. It extracts the type of the value the function returns (return).


Definition

In the standard library it's implemented like this:

javascript
type ReturnType<T extends (...args: any) => any> = T extends (...args: any) => infer R ? R : any;

This uses a conditional type with the infer operator to extract the type R that the function returns.


Usage examples

javascript
function getUser() { return { id: 1, name: "Alex" }; } type UserReturn = ReturnType<typeof getUser>; // { id: number; name: string } const u: UserReturn = { id: 2, name: "John" };
javascript
type Fn = (a: number, b: number) => string; type R = ReturnType<Fn>; // string

Which functions can be passed to ReturnType?

You can pass any type compatible with a function:

  • declared functions (function foo() {...})
  • arrow functions (() => number)
  • object methods ({ getName(): string })
  • function types (type Fn = () => boolean)
  • function signatures ((...args: string[]) => void)
  • even typeof someFunction

Examples of valid options:

javascript
type A = ReturnType<() => number>; // number type B = ReturnType<(x: string) => string[]>; // string[] type C = ReturnType<typeof Math.random>; // number type D = ReturnType<typeof Promise.resolve>; // Promise<unknown> type E = ReturnType<() => void>; // void

What happens if you pass a non-function?

TypeScript throws a compile error:

Type 'T' does not satisfy the constraint '(...args: any) => any'

Because the definition of ReturnType has the constraint:

javascript
T extends (...args: any) => any

This means T must be a function type. For example:

javascript
type Bad = ReturnType<string>; // Error: Type 'string' does not satisfy the constraint '(...args: any) => any'

Features and nuances

  • It also works with generic functions:

    javascript
    function wrap<T>(value: T) { return { value }; } type Wrapped = ReturnType<typeof wrap>; // { value: unknown } - the generic is erased to unknown
  • It works with async functions:

    javascript
    async function load() { return 42; } type R = ReturnType<typeof load>; // Promise<number>
  • It also works with overloaded functions, taking the return type of the last overload.


Summary

QuestionAnswer
What does ReturnType<T> do?Extracts the type of the value returned by function T.
Which functions can be passed?Any functions, methods, or signatures compatible with (...args: any) => any.
What happens if a non-function is passed?A type error - T must be a function.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.