Course contentsShow
← TypeScript
Lesson 644 of 1,79615. Generic ConstraintsFree lesson

Constraining to Conditional Outcomes

Using T extends SomeType ? TypeA : TypeB as a constraint to enforce specific type shapes based on conditions.

Constraining to Conditional Outcomes

What you'll learn: How to use conditional types directly inside extends clauses to enforce that a type parameter must match one of two specific shapes based on a condition.

The Core Idea

You've already seen conditional types (T extends SomeType ? TypeA : TypeB) and you've used extends in generic constraints. Now we combine them: instead of constraining to a single fixed type, you can constrain a type parameter to the outcome of a conditional type.

This means your constraint itself is "smart" — it evaluates to different required shapes depending on what T is.

Plain-English Analogy

Imagine a dress code that says: "If you're attending the daytime event, you must wear business casual or formal. If you're attending the evening event, you must wear formal or black tie." The constraint isn't just "wear clothes" — it adapts based on the event type.

Similarly, T extends (SomeCondition ? ShapeA : ShapeB) means: "T must look like ShapeA if the condition is true, or ShapeB otherwise."

Syntax Pattern

type ConditionalConstraint<T extends (T extends string ? { name: string } : { id: number })> = T;

Here, T must satisfy the conditional outcome: if T is a string, it must be { name: string }. Otherwise, it must be { id: number }. This enforces conditional shape requirements at the constraint level.

When This Matters

Use this when your generic needs to accept only types that conform to different structures depending on their nature — making your constraints adaptive rather than static.

Key Takeaway: You can use T extends (Condition ? TypeA : TypeB) as a constraint to enforce that a type parameter matches one of two specific shapes determined by a conditional check, making your generics context-aware and more precisely typed.