Generic constraints

Topic 3 of 3 in Generics7 min readIntermediateFree course

Overview

A plain type parameter T can be any type, so inside the function TypeScript won’t let you use any particular property of it. Constraints say “T can be any type, as long as it has this” — which lets the function body use exactly what it needs while staying generic.

The problem

TypeScript
function longest<T>(a: T, b: T): T {
  return a.length >= b.length ? a : b;
  // error TS2339: Property 'length' does not exist on type 'T'.
}

TypeScript is right: someone could call longest(1, 2), and numbers have no length.

extends: putting a limit on T

TypeScript
function longest<T extends { length: number }>(a: T, b: T): T {
  return a.length >= b.length ? a : b;
}

longest("tea", "coffee");     // string — "coffee"
longest([1, 2, 3], [4]);      // number[]
longest(1, 2);
// error TS2345: Argument of type 'number' is not assignable to parameter of type '{ length: number; }'.

T extends { length: number } means “T must have at least a numeric length property”. Strings, arrays and any object with length qualify. The function still returns the exact type that was passed in — string, not { length: number } — which is why a constraint is better than simply typing the parameters as { length: number }.

Constraints can be any type: an interface, a union, a primitive:

TypeScript
function byId<T extends { id: string }>(items: T[]): Map<string, T> { … }
function format<T extends string | number>(value: T): string { … }
function merge<A extends object, B extends object>(a: A, b: B): A & B {
  return { ...a, ...b };
}

keyof constraints: type-safe property access

The most useful constraint relates one type parameter to another:

Constraints: extends and keyof. In function getProp<T, K extends keyof T>(obj: T, key: K): T[K], K extends keyof T means K must be one of T’s keys, and T[K] is the type at that key. With const user = { name: “Asha”, age: 29 }, keyof typeof user is “name” | “age”. getProp(user, “name”) returns string; getProp(user, “age”) returns number; getProp(user, “email”) is an error. extends puts a limit on what T (or K) can be — so the function body may safely use what the limit promises. For example, <T extends { length: number }> lets the body read value.length for strings, arrays and more.

TypeScript
function getProp<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}

const user = { name: "Asha", age: 29 };
getProp(user, "name");    // string
getProp(user, "age");     // number
getProp(user, "email");
// error TS2345: Argument of type '"email"' is not assignable to parameter of type '"age" | "name"'.
  • keyof T is the union of T’s property names (keyof and typeof).
  • K extends keyof T limits the key to those names — and the editor autocompletes them.
  • T[K] is the type of the property at key K (Indexed access types), so the return type is exact.

This pattern powers many real APIs: sorting by a field, picking columns from a table, typed event emitters, form libraries:

TypeScript
function sortBy<T, K extends keyof T>(items: readonly T[], key: K): T[] {
  return [...items].sort((a, b) => (a[key] < b[key] ? -1 : a[key] > b[key] ? 1 : 0));
}

sortBy(products, "price");
sortBy(products, "prize");   // ✗ caught

Constraints with defaults

A type parameter can have both a constraint and a default:

TypeScript
type ApiError = { code: number; message: string };
type Result<T, E extends { message: string } = ApiError> =
  | { ok: true; value: T }
  | { ok: false; error: E };

Generic constraints in types

Constraints work in generic types and interfaces too:

TypeScript
interface Repository<T extends { id: string }> {
  findById(id: T["id"]): T | undefined;
  save(item: T): void;
}

type Repo1 = Repository<User>;     // ✓ User has id: string
type Repo2 = Repository<number>;
// error TS2344: Type 'number' does not satisfy the constraint '{ id: string; }'.

How much to constrain

Constrain by what the function uses, not by what you happen to call it with today:

TypeScript
// Too specific: only works for Products
function totalPrice(items: Product[]) { … }

// Just right: works for anything with a price
function totalPrice<T extends { price: number }>(items: T[]) {
  return items.reduce((sum, item) => sum + item.price, 0);
}

Then again, if a function doesn’t need to return the caller’s exact type, you may not need a generic at all — function totalPrice(items: { price: number }[]) accepts the same arguments thanks to structural typing. Use the generic version when the precise type must flow back out.

A common mistake: returning a “new T”

TypeScript
function withDefault<T extends { name: string }>(value: T): T {
  return { name: "Unknown" };
  // error TS2322: Type '{ name: string; }' is not assignable to type 'T'.
  //   '{ name: string; }' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint '{ name: string; }'.
}

The constraint is a minimum: T might be { name: string; age: number }, and an object with only name isn’t one of those. Return the value you were given (or a modified copy of it, { ...value, name: "Unknown" }), not a brand-new object.

Remember: extends says what a type parameter must at least have; K extends keyof T ties a key to an object; T[K] gives you the property’s type back.

Exercise

Type-safe helpers with constraints

Write four constrained generic functions: (1) longest<T extends { length: number }>(a: T, b: T): T; (2) getProp<T, K extends keyof T>(obj: T, key: K): T[K]; (3) sortBy<T, K extends keyof T>(items: readonly T[], key: K): T[] that returns a sorted copy (compare with < and >); (4) byId<T extends { id: string }>(items: readonly T[]): Map<string, T>. Use them on the products array: the longer of two strings and of two arrays, a product’s price (typed as number), products sorted by price and by name, and a lookup by id. Show with // @ts-expect-error that getProp(products[0], "colour") and longest(1, 2) are rejected.

TypeScript
type Product = { id: string; name: string; price: number };

const products: Product[] = [
  { id: "p1", name: "Lamp", price: 24.99 },
  { id: "p2", name: "Desk", price: 199 },
  { id: "p3", name: "Chair", price: 89.5 },
];

// 1. longest

// 2. getProp

// 3. sortBy

// 4. byId

Summary

  • Inside a generic function, an unconstrained T could be anything, so you can’t use any of its properties.
  • T extends Shape limits T to types that have at least that shape, and lets the body use it.
  • K extends keyof T restricts a parameter to the keys of another type; T[K] is the type of that property.
  • Constraints are checked at every call, giving precise errors for unsupported arguments.
  • Constrain only as much as the function actually needs — the more general, the more reusable.