What it Does

Extracts the return type of a function.

Syntax

type FunctionReturn = ReturnType<typeof functionName>;

Use Cases

Detailed Example


function getUser() {
  return {
    id: 1,
    name: "Alice",
    email: "alice@example.com"
  };
}

*// Extract return type automatically*
type User = ReturnType<typeof getUser>;
*// User is { id: number; name: string; email: string; }// Use the extracted type*
const user: User = {
  id: 2,
  name: "Bob",
  email: "bob@example.com"
};

Complex Example

function fetchConfig() {
  return {
    apiUrl: "<https://api.example.com>",
    timeout: 5000,
    retries: 3,
    features: {
      darkMode: true,
      notifications: {
        email: true,
        push: false
      }
    }
  };
}

*// Avoid manually typing this complex structure*
type AppConfig = ReturnType<typeof fetchConfig>;

*// Now use it anywhere*
function loadConfig(): AppConfig {
  return fetchConfig();
}

With Generic Functions

function createArray<T>(items: T[]) {
  return items;
}

type StringArray = ReturnType<typeof createArray<string>>;
*// StringArray is string[]*

Key Points