Course contentsShow
← TypeScript
Lesson 575 of 1,79613. GenericsFree lesson

Common Constraint Patterns

Explore real-world patterns like HasId, Comparable, and other common generic constraints.

Common Constraint Patterns

What you'll learn: How to recognize and use proven generic constraint patterns that solve recurring real-world problems.

As you build more TypeScript code, you'll notice certain constraint patterns appearing again and again. These aren't just random shapes—they're battle-tested solutions to common problems. Learning to recognize them is like learning design patterns: it speeds up your work and makes your intent clearer to other developers.

HasId: The Identity Pattern

One of the most common patterns is constraining to objects that have an id property:

interface HasId {
  id: string | number;
}

function findById<T extends HasId>(items: T[], id: string | number): T | undefined {
  return items.find(item => item.id === id);
}

This works with any object type that includes an id, making the function reusable across users, products, orders, etc.

Comparable: The Ordering Pattern

When you need to compare or sort items:

interface Comparable {
  compare(other: Comparable): number;
}

function sort<T extends Comparable>(items: T[]): T[] {
  return items.slice().sort((a, b) => a.compare(b));
}

HasLength: The Collection Pattern

Constraining to anything array-like:

function getFirst<T extends { length: number; [index: number]: unknown }>(collection: T) {
  return collection.length > 0 ? collection[0] : undefined;
}

This works with arrays, strings, and array-like objects.

The Named Entity Pattern

Combining multiple common properties:

interface NamedEntity {
  id: string;
  name: string;
}

function displayEntity<T extends NamedEntity>(entity: T): string {
  return `${entity.name} (${entity.id})`;
}

Key Takeaway: Common constraint patterns like HasId, Comparable, and HasLength create reusable contracts that work across different concrete types, making your generic code both flexible and type-safe.