Course contentsShow
← TypeScript
Lesson 541 of 1,79613. GenericsFree lesson

Type Parameter Inference

How TypeScript automatically infers type arguments from the values you pass to generic functions.

Type Parameter Inference

What you'll learn: How TypeScript automatically figures out generic type arguments from the values you pass, saving you from writing them explicitly.

The Automatic Guessing Game

You've learned how to write generic functions with type parameters like <T>. The great news? You rarely need to specify what T actually is. TypeScript looks at the arguments you pass and infers the type parameters automatically.

Think of it like a detective solving a puzzle: you give TypeScript the evidence (your function arguments), and it deduces the type without you spelling it out.

How It Works

When you call a generic function, TypeScript examines the actual values you provide and matches them against the function's parameters to determine what the type parameter should be:

function identity<T>(value: T): T {
  return value;
}

// TypeScript infers T = number
const num = identity(42);

// TypeScript infers T = string
const text = identity("hello");

// TypeScript infers T = boolean
const flag = identity(true);

Notice you didn't write identity<number>(42) — TypeScript figured it out from the value 42.

With Multiple Type Parameters

Inference works across multiple type parameters too:

function pair<T, U>(first: T, second: U): [T, U] {
  return [first, second];
}

// TypeScript infers T = string, U = number
const result = pair("age", 30);

TypeScript matched "age" to T and 30 to U automatically.

Why This Matters

Type parameter inference makes generics practical and ergonomic. You get all the type safety without the verbose syntax — the best of both worlds.

Key Takeaway: TypeScript automatically infers generic type parameters from the arguments you pass to generic functions, making them type-safe without requiring explicit type annotations at every call site.