Utility Types - ReturnType
In this page:
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
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
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
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
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
function fetchData() {
return { status: 200, body: "ok" };
}
type FetchResult = ReturnType<typeof fetchData>;
function handle(result: FetchResult) {
console.log(result.status);
}
handle(fetchData());
Chapter Quiz — Complete all 20 topics to unlock
0/20 topics done
Complete these topics first:
- TypeScript Advanced Types
- Mapped Types
- Conditional Types
- Custom Type Guards
- Assertion Functions
- Control Flow Analysis
- Exhaustiveness Checking
- Satisfies Operator
- Template Literal Types
- Utility Types - Partial
- Utility Types - Required
- Utility Types - Readonly
- Utility Types - Pick
- Utility Types - Omit
- Utility Types - Record
- Utility Types - Exclude and Extract
- Utility Types - NonNullable
- Utility Types - ReturnType
- Utility Types - Parameters
- TypeScript 5 Updates