Course contentsShow
← TypeScript
Lesson 601 of 1,79614. Generics in PracticeFree lesson

Inference from Function Arguments

How TypeScript infers type parameters based on the types of values passed to generic functions.

Inference from Function Arguments

What you'll learn: How TypeScript automatically figures out generic type parameters by looking at the values you pass into a function.

When you call a generic function, you can explicitly tell TypeScript what the type parameter should be using angle brackets (<T>), but most of the time you don't need to. TypeScript is smart enough to infer the type parameter from the arguments you actually pass.

How It Works

Imagine you have a generic identity function:

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

When you call it like this:

const result = identity(42);

TypeScript looks at the argument (42), sees it's a number, and infers that T must be number. You didn't need to write identity<number>(42) — TypeScript connected the dots automatically.

The Matching Process

TypeScript compares the actual argument types with the parameter types in the function signature. Wherever it sees a type parameter like T, it tries to match it with the concrete type from your argument.

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

const coordinates = pair(10, 20);      // T inferred as [number, number]
const mixed = pair("hello", true);     // T inferred as [string, boolean]

This inference happens at the call site, every time you invoke the function with arguments.

Key Takeaway: TypeScript infers generic type parameters by examining the types of arguments you pass, saving you from writing explicit type arguments while maintaining full type safety.