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

  1. Generic parameter<T>
    • T is a generic type. It can be any type, but this utility is meant to be used with function types.

  1. Conditional typeT extends (...args: any[]) => infer R ? R : never This means:
    • If T is a function type (something like (args) => returnType), then infer its return type as R.
    • Otherwise, give never.

  1. 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 variable R that represents the return type of the function.

  1. The result
    • If T is a function, R (the inferred return type) is returned.
    • If T is not a function, the result is never.

✅ 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)

By davs