Generic Constraints
A generic constraint limits what types may fill a type parameter, written T extends Shape. Inside the generic, you may use the members Shape guarantees.
Detailed Explanation
An unconstrained type parameter is a black box. You can store it, return it, and put it in a structure. You cannot read .length or .id, because the caller might pass a boolean. A constraint is the contract that makes those reads legal.
function longest<T extends { length: number }>(a: T, b: T): T {
return a.length >= b.length ? a : b;
}
T extends { length: number } means "any type that is assignable to { length: number }." Strings qualify. Arrays qualify. { length: number; label: string } qualifies. Numbers do not. Inside the function, a.length is a number. The return type is still T, so longest("ada", "grace") is a string, not { length: number }. That last part is the reason to use a generic instead of writing the constraint as the parameter type directly.
extends here is not class inheritance. It is assignability. T extends string accepts the type string and every string literal. T extends "get" | "post" accepts those two literals and unions of them. T extends any[] accepts every array type.
The most common constraint in application code is T extends object or a specific interface. The most common constraint in library code is K extends keyof T: a second parameter that must be a key of the first. That is how Pick is written, and how a function can take an object and one of its property names and return the property's type.
Constraints can refer to earlier parameters: <T, K extends keyof T>. They cannot refer to later ones. Defaults, if any, come after constraints.
A constraint that is too tight makes the generic pointless — you might as well have written a concrete type. A constraint that is too loose leaves you asserting. The test is: does the body need a member? Put that member on the constraint. Does the body only store and return the value? Leave T unconstrained.
Two traps. T extends string | number does not let you call string methods, because T might be a number; you still have to narrow. And T extends any is not a constraint, it is giving up — every type extends any, and you get no members that are safe to use without also inheriting any's unsafety.
Code Examples
1. Constraint gives you a member; the generic keeps the precise type.
// 1. Constraint gives you a member; the generic keeps the precise type.
function longest<T extends { length: number }>(a: T, b: T): T {
return a.length >= b.length ? a : b;
}
const name = longest("ada", "lovelace"); // string
const row = longest([1, 2], [3, 4, 5]); // number[]
// longest(10, 20);
// Error: number does not satisfy { length: number }2. K extends keyof T — a typed property read.
// 2. K extends keyof T — a typed property read.
function getProp<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const user = { id: 7, email: "ada@example.com" };
const email = getProp(user, "email"); // string
// getProp(user, "name");
// Error: Argument of type '"name"' is not assignable to parameter of type '"id" | "email"'.3. You still narrow when the constraint is a union.
// 3. You still narrow when the constraint is a union.
function stringifyId<T extends string | number>(id: T): string {
if (typeof id === "number") {
return id.toFixed(0);
}
return id.toUpperCase();
}
console.log(stringifyId(42)); // "42"
console.log(stringifyId("abc")); // "ABC"Common Gotchas
`T extends A | B` does not mean `T` is both
it means `T` is assignable to the union. Members unique to `A` are not available until you narrow.
`T extends any` disables checking on `T`
it is not a real constraint. Use `unknown` if you need a top bound, or name the members you actually read.
`extends` in a constraint is assignability, not inheritance
primitive unions, aliases, and structural object types all work. A class hierarchy is only one way to satisfy it.
Circular constraints fail or infer as `unknown`
`T extends Factory<T>` is sometimes expressible and often a sign you want an interface with a method instead.