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

Constraints on inferred Types

Applying extends constraints to infer clauses to ensure extracted types meet specific requirements.

Constraints on inferred Types

You'll learn how to apply extends constraints to infer clauses, ensuring the types you extract meet specific requirements before TypeScript captures them.

What This Solves

When using infer to extract types from complex structures, you sometimes need to ensure the inferred type matches certain criteria. Without constraints, infer will capture anything that fits the pattern — but you might only want types that satisfy specific conditions.

Think of it like a quality-control checkpoint: instead of accepting any package that arrives at your warehouse, you only accept packages that meet certain size or weight requirements.

How Constraints Work with infer

You apply constraints using extends directly on the infer clause:

type ExtractStringArray<T> = 
  T extends Array<infer U extends string> 
    ? U 
    : never;

// U will only be inferred if it's assignable to string
type A = ExtractStringArray<string[]>;     // string
type B = ExtractStringArray<number[]>;     // never (constraint failed)
type C = ExtractStringArray<(string | number)[]>;  // never

Here, infer U extends string means "extract U, but only if it's a string". If the constraint isn't met, the whole condition fails.

Practical Example: Safe Promise Unwrapping

type UnwrapObjectPromise<T> = 
  T extends Promise<infer U extends object>
    ? U
    : never;

type Result1 = UnwrapObjectPromise<Promise<{ id: number }>>;  // { id: number }
type Result2 = UnwrapObjectPromise<Promise<string>>;  // never (string isn't object)

This ensures you only unwrap promises that resolve to objects, not primitives.

Combining Multiple Constraints

type ExtractNonNullableArray<T> = 
  T extends Array<infer U extends NonNullable<unknown>>
    ? U
    : never;

type Safe = ExtractNonNullableArray<string[]>;  // string
type Unsafe = ExtractNonNullableArray<(string | null)[]>;  // never

Key Takeaway: Constraints on infer clauses let you validate extracted types during the inference process itself, making your conditional types safer and more predictable by rejecting patterns that don't meet your requirements.