What does ReturnType<T> do?
What does ReturnType<T> do?
ReturnType<T> is a built-in TypeScript utility type that returns the result type of function T.
It extracts the type of the value the function returns (return).
Definition
In the standard library it's implemented like this:
type ReturnType<T extends (...args: any) => any> =
T extends (...args: any) => infer R ? R : any;This uses a conditional type with the infer operator to extract the type R that the function returns.
Usage examples
function getUser() {
return { id: 1, name: "Alex" };
}
type UserReturn = ReturnType<typeof getUser>;
// { id: number; name: string }
const u: UserReturn = { id: 2, name: "John" };type Fn = (a: number, b: number) => string;
type R = ReturnType<Fn>; // stringWhich functions can be passed to ReturnType?
You can pass any type compatible with a function:
- declared functions (
function foo() {...}) - arrow functions (
() => number) - object methods (
{ getName(): string }) - function types (
type Fn = () => boolean) - function signatures (
(...args: string[]) => void) - even
typeof someFunction
Examples of valid options:
type A = ReturnType<() => number>; // number
type B = ReturnType<(x: string) => string[]>; // string[]
type C = ReturnType<typeof Math.random>; // number
type D = ReturnType<typeof Promise.resolve>; // Promise<unknown>
type E = ReturnType<() => void>; // voidWhat happens if you pass a non-function?
TypeScript throws a compile error:
Type 'T' does not satisfy the constraint '(...args: any) => any'
Because the definition of ReturnType has the constraint:
T extends (...args: any) => anyThis means T must be a function type.
For example:
type Bad = ReturnType<string>;
// Error: Type 'string' does not satisfy the constraint '(...args: any) => any'Features and nuances
-
It also works with generic functions:
javascriptfunction wrap<T>(value: T) { return { value }; } type Wrapped = ReturnType<typeof wrap>; // { value: unknown } - the generic is erased to unknown -
It works with
asyncfunctions:javascriptasync function load() { return 42; } type R = ReturnType<typeof load>; // Promise<number> -
It also works with overloaded functions, taking the return type of the last overload.
Summary
| Question | Answer |
|---|---|
What does ReturnType<T> do? | Extracts the type of the value returned by function T. |
| Which functions can be passed? | Any functions, methods, or signatures compatible with (...args: any) => any. |
| What happens if a non-function is passed? | A type error - T must be a function. |
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.