Hack Frontend Community

Utility Type ReturnType in TypeScript

ReturnType is a utility type in TypeScript that determines what type a function returns. It helps avoid duplication and automatically adjusts if the function changes.


Syntax

ReturnType<T>
  • T — type (or reference to the function itself) from which we want to get the return value type.

TypeScript calculates the type that the function actually returns and passes it to ReturnType output.


Usage Example

Extracting function return type

function createUser(name: string, age: number) {
  return {
    name,
    age,
    createdAt: new Date(),
  };
}

type UserFromFunction = ReturnType<typeof createUser>;
  • Function createUser returns object { name, age, createdAt }.
  • ReturnType<typeof createUser> extracts exact type of this object (e.g., { name: string, age: number, createdAt: Date }).

Typing helper functions

If you have helper functions that process result from another function, you can directly use ReturnType:

function processUserData(user: ReturnType<typeof createUser>) {
  console.log(user.name, user.createdAt);
  // ...
}
  • processUserData will receive object with same type that createUser returns, ensuring consistency and avoiding type duplication.

Why ReturnType is Needed

  1. Simplification: No need to manually declare or duplicate return value type.
  2. Synchronization: If createUser function logic changes, ReturnType will automatically adjust, eliminating desynchronization risk.
  3. Flexibility: Convenient for factories or "wrappers" around functions where you need to know what exactly the original function returns.

Compatibility with Other Utilities

Sometimes ReturnType is combined with InstanceType, Parameters or other utilities (e.g., for building more complex types depending on function results).


Notes:

  1. ReturnType doesn't work with some scenarios of "complex" overload functions when a function has multiple overload variants. In such cases TypeScript will try to infer a generalized or "merged" type.
  2. If function uses generic types, ReturnType may require more careful approach to account for specific specialization.

Summary

  • ReturnType simplifies extracting function return value type, allowing avoiding duplication and increasing code consistency.