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

Using Conditionals in extends Clauses

How to use conditional types directly in generic constraints to limit type parameters based on conditions.

Using Conditionals in extends Clauses

What You'll Learn

You'll learn how to use conditional types directly inside generic constraints to allow or reject type parameters based on logical conditions.

The Core Idea

TypeScript lets you write conditional logic right in your extends clause using the syntax T extends Condition ? TypeA : TypeB. This means your constraint can dynamically change based on what type is passed in, making your generics smarter and more flexible.

Think of it like a bouncer at a club who doesn't just check IDs, but applies different rules based on who's trying to enter. If you're wearing sneakers, different dress code applies than if you're wearing formal shoes.

How It Works

Instead of a simple constraint like T extends string, you can write:

function process<T extends T extends string ? string : number>(value: T): T {
  return value;
}

This constraint says: "If T is a string type, constrain it to string. Otherwise, constrain it to number."

Here's a more practical example:

function wrapInArray<T extends T extends any[] ? T : never>(
  value: T
): T {
  return value;
}

// Works with arrays
wrapInArray([1, 2, 3]); // OK

// Fails with non-arrays
// wrapInArray(42); // Error: number doesn't extend never

This pattern forces T to be an array type — if it's not an array, the constraint becomes never, which nothing satisfies.

Common Patterns

You can use this to create type gates that only accept certain shapes:

type IsFunction<T> = T extends Function ? T : never;

function callIt<T extends IsFunction<T>>(fn: T): void {
  // We know T is definitely a function here
}

Key Takeaway: Conditional types in extends clauses let you apply dynamic constraints that change based on the type argument, enabling context-aware generic type safety.