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:
- TypeScript checks if
Tmatches the patternPattern<something> - The
infer Udeclares a new type variableUthat captures whatever matches that position - If the match succeeds,
Uis available in the true branch - If the match fails, the false branch executes (and
Udoesn'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.