Constraints on infer Variables
What you'll learn: How to add extends constraints to infer variables and what happens when TypeScript can't satisfy those constraints.
The Core Idea
Just like regular type parameters, infer variables can be constrained using extends. This tells TypeScript: "Only infer values that satisfy this constraint — otherwise, fall back to something else."
The syntax looks like this:
type MyType<T> = T extends SomePattern<infer U extends Constraint>
? U
: Fallback;
Here, U will only be inferred if it also satisfies Constraint. If TypeScript can't find a valid U that meets both the pattern and the constraint, the conditional resolves to the false branch.
Why Constrain infer?
Without constraints, infer captures whatever matches the pattern — even if it's not useful. Constraints let you narrow what gets inferred, improving type safety and preventing nonsensical types.
Example: Extracting only string properties
type FirstStringArg<T> = T extends (first: infer F extends string, ...args: any[]) => any
? F
: never;
type A = FirstStringArg<(name: string, age: number) => void>; // string
type B = FirstStringArg<(count: number) => void>; // never
Here, F is only inferred if it's a string. If the first parameter is number, the constraint fails and the type resolves to never.
What Happens When Constraints Conflict
If TypeScript can't infer a type that satisfies both the structural pattern and the constraint, the entire conditional resolves to the false branch:
type OnlyStringArray<T> = T extends Array<infer E extends string>
? E[]
: never;
type C = OnlyStringArray<string[]>; // string[]
type D = OnlyStringArray<number[]>; // never
For number[], TypeScript can't infer E as string, so the whole thing fails gracefully.
Key Takeaway
Constraining infer variables with extends lets you specify what kinds of types can be captured — if the constraint can't be met, the conditional type falls through to the false branch, giving you precise control over type extraction.