← Back to TypeScript Course | Chapter 8: Advanced Types | Lesson 18 of 20

Utility Types - ReturnType

ReturnType<T> extracts the return type of a function type. It is useful when another type needs to stay synchronized with a function's result.

Basic ReturnType

ReturnType<T> extracts the type produced by a function type T, which is useful when another part of the code needs to reuse that exact return type without duplicating it by hand.

Example: Basic ReturnType

typescript
function createUser() {
  return { id: 1, name: "Ravi" };
}
type User = ReturnType<typeof createUser>;
const u: User = { id: 2, name: "Priya" };
console.log(u);

ReturnType with Object Results

ReturnType can extract complete object shapes from functions, so if a function returns a rich object, ReturnType captures that entire shape automatically as a reusable type.

Example: ReturnType with Object Results

typescript
function getConfig() {
  return { host: "localhost", port: 8080 };
}
type Config = ReturnType<typeof getConfig>;
const c: Config = { host: "example.com", port: 443 };
console.log(c);

ReturnType with Arrow Functions

ReturnType works with arrow functions too, but since arrow function *values* aren't types on their own, typeof myArrowFn is used to obtain the function type ReturnType needs as its argument.

Example: ReturnType with Arrow Functions

typescript
const getPoint = () => ({ x: 1, y: 2 });
type Point = ReturnType<typeof getPoint>;
const p: Point = { x: 5, y: 5 };
console.log(p);

ReturnType with Generic Functions

ReturnType can also be used with generic functions, although the extracted result may preserve unresolved type parameters rather than a single concrete type, depending on how the generic function is defined.

Example: ReturnType with Generic Functions

typescript
function wrap<T>(value: T) {
  return { value };
}
type Wrapped = ReturnType<typeof wrap<string>>;
const w: Wrapped = { value: "hi" };
console.log(w);

When to Use ReturnType

Use ReturnType when a type should automatically follow changes to a function's actual return type, so editing the function later keeps the derived type in sync without a manual update.

Example: When to Use ReturnType

typescript
function fetchData() {
  return { status: 200, body: "ok" };
}
type FetchResult = ReturnType<typeof fetchData>;
function handle(result: FetchResult) {
  console.log(result.status);
}
handle(fetchData());

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.