Generic constraints
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
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
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:
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:
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 Tis the union of T’s property names (keyof and typeof).K extends keyof Tlimits 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:
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"); // ✗ caughtConstraints with defaults
A type parameter can have both a constraint and a default:
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:
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:
// 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”
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:
extendssays what a type parameter must at least have;K extends keyof Tties a key to an object;T[K]gives you the property’s type back.
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.
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. byIdtype 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
function longest<T extends { length: number }>(a: T, b: T): T {
return a.length >= b.length ? a : b;
}
// 2. getProp
function getProp<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
// 3. sortBy
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));
}
// 4. byId
function byId<T extends { id: string }>(items: readonly T[]): Map<string, T> {
return new Map(items.map((item) => [item.id, item]));
}
console.log(longest("tea", "coffee"), longest([1, 2, 3], [4])); // coffee [ 1, 2, 3 ]
const lamp = products[0];
if (lamp) {
const price: number = getProp(lamp, "price");
console.log(price); // 24.99
}
console.log(sortBy(products, "price").map((p) => p.name)); // [ 'Lamp', 'Chair', 'Desk' ]
console.log(sortBy(products, "name").map((p) => p.name)); // [ 'Chair', 'Desk', 'Lamp' ]
console.log(byId(products).get("p2")?.name); // Desk
function rejected(p: Product) {
// @ts-expect-error -- "colour" is not a key of Product
getProp(p, "colour");
// @ts-expect-error -- numbers have no length
longest(1, 2);
}Summary
- Inside a generic function, an unconstrained
Tcould be anything, so you can’t use any of its properties. T extends Shapelimits T to types that have at least that shape, and lets the body use it.K extends keyof Trestricts 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.