TypeScript Course
TypeScript
/
Advanced

ReturnType<T>

Definition

A utility type that extracts the exact return type of a function type `T` using the `infer` keyword internally.

Explain Like I'm New

If you are using a 3rd-party library function that returns a massive, complex object, but the library author forgot to export the Type for that object, `ReturnType` rescues you. You wrap the function in it, and TS extracts the return object's blueprint for you to use.

Real World Example

Typing Redux actions. Redux involves writing many action creator functions. Instead of manually writing interfaces for what every action returns, you just use `ReturnType<typeof myActionCreator>`.

Common Use Cases

  • •Extracting types from 3rd party functions
  • •Redux/Zustand state typing
  • •Keeping code DRY

Interactive Example

// A complex function (Imagine this comes from an external library)
function createComplexUser(name: string, age: number) {
  return {
    id: Math.random(),
    profile: { name, age },
    isActive: true,
    roles: ["user"]
  };
}

// We want to type a variable to hold the result of that function,
// but we don't want to manually type out that massive object interface.
// SOLUTION:
type UserData = ReturnType<typeof createComplexUser>;

const user: UserData = {
  id: 123,
  profile: { name: "Alice", age: 30 },
  isActive: false,
  roles: ["admin"]
};

Interview Questions

basic

  • How do you use `ReturnType` on an actual JavaScript function?

intermediate

  • What happens if you use `ReturnType` on a generic function?

Flash Cards

Question

How do you use it on an actual function?

Click to reveal answer
Answer

You MUST combine it with `typeof`. `ReturnType` expects a TYPE as an argument, not a value. So you write `type Data = ReturnType<typeof fetchUserData>;`.