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

Combining Multiple Constraints with &

Learn how to compose multiple constraints using intersection types to require type parameters meet all conditions.

Combining Multiple Constraints with &

You'll learn how to require a type parameter to satisfy multiple conditions simultaneously using intersection types in generic constraints.

The Core Idea

Sometimes a single extends constraint isn't enough. You might need a type parameter to be both something with specific properties and something with other properties. TypeScript lets you combine multiple constraints using the & operator (intersection) within the extends clause.

Think of it like job requirements: you might need someone who is "both a certified driver AND a licensed electrician." Similarly, you can require a type parameter to match multiple shapes at once.

Basic Syntax

function process<T extends HasName & HasAge>(item: T) {
  console.log(`${item.name} is ${item.age} years old`);
  return item;
}

type HasName = { name: string };
type HasAge = { age: number };

Here, T must satisfy both HasName and HasAge. The type parameter must have both a name property and an age property.

Real-World Example

type Identifiable = { id: string };
type Timestamped = { createdAt: Date };

function saveEntity<T extends Identifiable & Timestamped>(entity: T) {
  console.log(`Saving entity ${entity.id} from ${entity.createdAt}`);
  return entity;
}

// Works: has both properties
saveEntity({ id: "123", createdAt: new Date(), extra: "data" });

// Error: missing createdAt
// saveEntity({ id: "456" });

When to Use This Pattern

This is powerful when building utilities that need guarantees about multiple, independent aspects of a type—like entities that must be both identifiable and auditable, or objects that must be both serializable and validatable.

Key Takeaway: Use & in generic constraints to require type parameters meet all specified conditions simultaneously, enabling precise type safety for complex requirements.