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>Tis 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 : neverThis means:- If
Tis 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 Ris special — it introduces a new type variableRthat represents the return type of the function.
- The result
- If
Tis a function,R(the inferred return type) is returned. - If
Tis not a function, the result isnever.
- If
✅ Example usage
function greet(name: string): string {
return `Hello, ${name}`;
}
type GreetReturn = ReturnType<typeof greet>;
// GreetReturn = stringAnother example:
type Foo = ReturnType<() => number>;
// Foo = number
type Bar = ReturnType<string>;
// Bar = never (because string is not a function)