Example Expression in TypeScript :
type ReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
This is the built-in ReturnType
type, redefined in its raw form. It extracts the return type of a function type.
🔎 Step-by-step explanation
- Generic parameter
<T>
T
is a generic type. It can be any type, but this utility is meant to be used with function types.
- Conditional type
T extends (...args: any[]) => infer R ? R : never
This means:- If
T
is a function type (something like(args) => returnType
), then infer its return type asR
. - Otherwise, give
never
.
- If
- Function check
(...args: any[]) => infer R
(...args: any[])
means “a function with any number of parameters of any type.”infer R
is special — it introduces a new type variableR
that represents the return type of the function.
- The result
- If
T
is a function,R
(the inferred return type) is returned. - If
T
is not a function, the result isnever
.
- If
✅ Example usage
function greet(name: string): string {
return `Hello, ${name}`;
}
type GreetReturn = ReturnType<typeof greet>;
// GreetReturn = string
Another example:
type Foo = ReturnType<() => number>;
// Foo = number
type Bar = ReturnType<string>;
// Bar = never (because string is not a function)