Web Developer

|

Stockholm, Sweden

Delivering scalable solutions for
startups, enterprises, and agencies.

Generic Constraints

What are Generic Constraints?

Generic constraints let you limit what types your generics can accept. Instead of accepting any type, you can specify "only types that have certain properties" - making your code safer and more predictable.

generic

The kitchen analogy

Imagine a kitchen machine that can
any ingredient. Generics are like that machine - they accept any type. But for a fruit salad, you only want fruits, not random ingredients. Generic constraints are like setting the machine to

Why use constraints?

  • Type safety - Prevent errors by ensuring types have required properties
  • Better intellisense - TypeScript knows what properties are available
  • Clear intentions - Code explicitly states what types are acceptable

Basic constraint syntax

Use extends to constrain your generics to types that have specific properties.

function displayPrice<T extends { price: number }>(item: T) - Now TypeScript guarantees that item.price exists and won't complain when you access it.

Common constraint patterns

  • T extends string - Only string types
  • T extends { id: number } - Only objects with an id property
  • T extends keyof User - Only keys that exist on the User type

Default types

You can also set fallback types when no generic is specified.

function process<T = string>(item: T) - If no type is provided, TypeScript assumes string. Like setting your kitchen machine to make apple salad by default.

Real-world benefits

  • Catch errors early - TypeScript prevents you from passing invalid types
  • Flexible yet safe - Accept multiple types whilst ensuring they meet requirements
  • Self-documenting - Constraints show exactly what your function expects
Web Developer
Harry Yates 2025®