Course contentsShow
← TypeScript
Lesson 1434 of 1,79633. Inference Inversion PatternsFree lesson

What infer Actually Does

Understanding how infer creates type variables within conditional types to extract portions of matched types.

What infer Actually Does

You'll learn how TypeScript's infer keyword creates temporary type variables inside conditional types to capture and extract portions of matched patterns.


The Core Mechanism

Think of infer as a pattern-matching capture group for types. When you write a conditional type with T extends SomePattern, you can use infer to say "match this pattern, and capture part of it as a new type variable I can use in the true branch."

Without infer, you can only check if a type matches a pattern. With infer, you can extract pieces of that pattern and work with them.

How It Works

The syntax looks like this:

type Example<T> = T extends Pattern<infer U> ? U : never;

Here's what happens:

  1. TypeScript checks if T matches the pattern Pattern<something>
  2. The infer U declares a new type variable U that captures whatever matches that position
  3. If the match succeeds, U is available in the true branch
  4. If the match fails, the false branch executes (and U doesn't exist there)

A Simple Example

type GetArrayElement<T> = T extends Array<infer Element> ? Element : never;

type A = GetArrayElement<string[]>;  // string
type B = GetArrayElement<number[]>;  // number
type C = GetArrayElement<string>;    // never (not an array)

When T is string[], TypeScript matches it against Array<infer Element>, binding Element to string. That captured Element type is then returned.

Key Insight

infer doesn't "run" or "execute" — it's part of the pattern matching that happens during type checking. It creates a placeholder variable that TypeScript fills in when it successfully matches your pattern.

Key Takeaway: infer creates temporary type variables within conditional type patterns, allowing you to extract and reuse portions of matched types — it's pattern matching with capture groups for the type system.