Back

TypeScript ReturnType Utility Type

`ReturnType< T >` extracts and allows you to use the return type of a given function type.

Basic Example

function getUser() {
    return { id: 1, name: "Alice", age: 30 };
  }
  
  type User = ReturnType<typeof getUser>;
  
  const user1: User = { id: 2, name: "Bob", age: 25 };
  // const user2: User = { id: 3, name: "Charlie" }; // Error: age not assigned

You can automatically capture a function’s return type and reuse it in other type definitions.

Using ReturnType for Type Safety

function calculateTotal(price: number, quantity: number) {
    return price * quantity;
  }
  
  type Total = ReturnType<typeof calculateTotal>;
  
  const totalAmount: Total = 100;
  // const wrongTotal: Total = "100"; // Error: cannot be string

Assigning incompatible data with the function's return type will cause compile-time errors.

Usage with Async Functions

type AsyncFunction = () => Promise<string>;
  
  type ResultType = ReturnType<AsyncFunction>;
  // ResultType = Promise<string>
  
  async function asyncFunc(): Promise<string> {
    return "hello";
  }
  
  asyncFunc().then(result => {
    console.log(result); // "hello"
  });

For functions returning a Promise, the return type is captured as `Promise< T >`, allowing safe operations on it.

Why Use ReturnType?

`ReturnType` improves type consistency and maintenance by inferring function return types automatically instead of manually specifying them.

Back