What infer Does
You'll learn: How to use infer to create type variables within conditional types that capture portions of matched types.
The Core Idea
Think of infer as a type-level "capture group" — like regex capture groups, but for types. When TypeScript checks whether a type extends a pattern, infer lets you say "if this matches, save this part of the type into a variable I can use later."
Without infer, you can only check if a type matches a pattern. With infer, you can extract pieces of that type for reuse.
How It Works
The infer keyword only appears in the extends clause of a conditional type. It introduces a new type variable that TypeScript will try to infer from the type being checked.
type GetReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
type Example1 = GetReturnType<() => string>; // string
type Example2 = GetReturnType<() => number>; // number
type Example3 = GetReturnType<string>; // never
Here, infer R means: "if T is a function type, capture its return type as R." The R is then available in the true branch.
The Pattern
type MyConditional<T> = T extends SomePattern<infer U> ? U : FallbackType;
infer Ucreates a type variableU- TypeScript infers what
Ushould be based on what matches - You can use
Uin the true branch only Uis scoped to that specific branch
Key Takeaway: infer creates type variables within conditional type branches, letting you capture and extract parts of matched types for use in the result type.