Typescript Foundations / Utility Types

ReturnTypes

🔄 ReturnType<T>

ReturnType<T> extracts the return type of a function.

It is useful when you want to reuse a function's return type without defining it manually.

🔹 Example

function getUser() {
  return {
    name: "Bhaskar",
    age: 25
  };
}

type User = ReturnType<typeof getUser>;

const user: User = {
  name: "Rahul",
  age: 30
};

Here, TypeScript automatically infers:

type User = {
  name: string;
  age: number;
};

So if the return value of getUser() changes later, the User type automatically updates as well.

💡 Common Use

ReturnType is useful when working with utility functions, APIs, callbacks, and existing functions whose return type you want to reuse.

Remember: ReturnType<T> → Gets the return type of a function.