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

When TypeScript Infers Type Arguments

How the compiler automatically determines generic type parameters from usage context and function arguments.

When TypeScript Infers Type Arguments

You'll learn: How TypeScript automatically figures out what types to use for generic type parameters, saving you from writing them explicitly every time.

The Magic of Automatic Type Resolution

When you call a generic function, TypeScript doesn't always need you to spell out the type arguments in angle brackets. Instead, the compiler looks at the actual values you pass and determines what types make sense for the type parameters.

Think of it like a detective examining clues: if you hand a function the number 42, TypeScript concludes "Ah, T must be number!" This process is called type argument inference.

How It Works

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

// TypeScript infers T = number from the argument
const num = identity(42); // T becomes number

// TypeScript infers T = string from the argument
const str = identity("hello"); // T becomes string

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

Notice you didn't write identity<number>(42)—TypeScript figured it out! The compiler examines the argument type and uses it to solve for T.

Multiple Type Parameters

With multiple type parameters, TypeScript infers each one from its corresponding usage:

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

// T inferred as number, U inferred as string
const result = pair(10, "ten");

When Inference Happens

Type argument inference occurs whenever:

  • Function arguments match type parameters
  • Return values flow into typed variables
  • Generic constraints provide enough context

You can still provide explicit type arguments when inference fails or when you want to override the inferred types: identity<string>(42) (though this would error!).

Key Takeaway: TypeScript infers generic type arguments from the values you pass at call sites, making generics convenient without sacrificing type safety.