Generic Constraints
In this page:
Basic Generic Constraint
A generic parameter can extend an object shape (T extends { length: number }, for example) to guarantee that whatever type is used has at least the required properties the function's body relies on.
Example: Basic Generic Constraint
function printLength<T extends { length: number }>(value: T): void {
console.log(value.length);
}
printLength("hello");
printLength([1, 2, 3]);
Constraints with Primitive Types
A type parameter can be constrained to a primitive type such as number or string, limiting what callers are allowed to supply while still keeping the function generic across the values within that constraint.
Example: Constraints with Primitive Types
function double<T extends number>(value: T): number {
return value * 2;
}
console.log(double(21));
Constraints with Object Shapes
Object constraints let generic functions access required properties while still allowing the caller's actual argument to have additional, unrelated properties beyond what the constraint specifies.
Example: Constraints with Object Shapes
function printName<T extends { name: string }>(obj: T): void {
console.log(obj.name);
}
printName({ name: "Tom", age: 30 }); // extra properties allowed
Interface-Based Constraints
Interfaces provide reusable shapes that can be used as generic constraints, so a constraint can be defined once and reused across many different generic functions or classes instead of repeating an inline object shape.
Example: Interface-Based Constraints
interface HasId {
id: number;
}
function printId<T extends HasId>(item: T): void {
console.log(item.id);
}
printId({ id: 7, name: "Item" });
Why Constraints Matter
Constraints provide flexibility without giving up type safety — they let generic code accept a wide range of types while still guaranteeing the compiler that certain properties or methods will be present.
Example: Why Constraints Matter
function getLength<T extends { length: number }>(value: T): number {
return value.length; // guaranteed to exist because of the constraint
}
console.log(getLength("hello"), getLength([1, 2]));
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: