Skip to content

Generic Constraints

Medium — good to knowGeneral Dev

ELI5 — The Vibe Check

Generic constraints are like telling a restaurant 'I'll eat anything... as long as it has cheese.' You keep the flexibility of generics but add rules about what types are allowed in. TypeScript respects the rules and blocks anything that doesn't qualify.

Real Talk

TypeScript's mechanism for restricting generic type parameters using the 'extends' keyword. Constraints ensure that generic types meet certain structural requirements, enabling safe access to properties and methods while maintaining type flexibility.

Show Me The Code

interface HasId {
  id: number;
}

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

// Works with any type that has an 'id' property
findById([{ id: 1, name: 'Alice' }], 1);

When You'll Hear This

"Add a generic constraint so the function only accepts objects with an id field." / "T extends Record<string, unknown> ensures the generic is always an object."

Made with passive-aggressive love by manoga.digital. Powered by Claude.