Sub topic 2
Restricting a Type Parameter with `extends`
Assume you know basic TypeScript types, interfaces, type aliases, and simple generic functions. You should also be comfortable reading object types and union types.
A generic type parameter is unconstrained by default. For example:
function first<T>(items: T[]): T {
return items[0];
}Inside first, TypeScript knows that items contains values of type T. However, it knows nothing else about T. It cannot assume that T has a length property, a name property, or any particular method.
Why unconstrained type parameters are limiting
This function does not compile:
function longer<T>(a: T, b: T): T {
// return a.length >= b.length ? a : b;
return a;
}The compiler rejects the commented line because T could be any type, including number or boolean. An unconstrained type parameter does not guarantee that the values have a length property.
You can restrict T with an extends constraint. A constraint describes the minimum structure that every valid T must provide.
Adding a shape constraint
function longest<T extends { length: number }>(a: T, b: T): T {
return a.length >= b.length ? a : b;
}
console.log(longest([1, 2, 3], [1, 2])); // [1, 2, 3]
console.log(longest("ab", "abc")); // "abc"
// longest(10, 20); // Error: number does not have a length propertyThe declaration T extends { length: number } means:
Tmay be the exact type{ length: number }.Tmay be a more specific object type with a numericlength.Tmay be an array or a string, because both have a numericlength.Tcannot be a type that lackslength.
The constraint gives the function body permission to read a.length and b.length. The return type is still T, so the function preserves the original specific type rather than returning only { length: number }.
Constraining object shapes
You can name a required shape with an interface or type alias:
interface Identifiable {
id: number;
}
function getId<T extends Identifiable>(value: T): number {
return value.id;
}
const user = { id: 7, name: "Ada" };
const order = { id: 42, total: 19.99 };
console.log(getId(user)); // 7
console.log(getId(order)); // 42Both objects contain the required id: number property. Each object can also contain additional properties. The constraint checks the minimum shape, not an exact shape.
A constraint can include several required members:
type Printable = {
print(): string;
};
function show<T extends Printable>(value: T): void {
console.log(value.print());
}
const report = {
title: "Status",
print() {
return this.title;
}
};
show(report);The argument must have a callable print member that returns a string.
Constraining a type to a union
A constraint can limit a type parameter to a set of allowed types:
function formatValue<T extends string | number>(value: T): string {
return String(value);
}
console.log(formatValue("ready"));
console.log(formatValue(200));
// formatValue(true); // Error: boolean is not allowedInside the function, TypeScript knows that value is either a string or a number. It does not know which one at every point, so you can use operations that both types support, such as converting either value with String.
A union constraint is useful when an API accepts several related types. An object-shape constraint is useful when the implementation needs particular properties or methods.
Visual model
Common errors
A constraint does not turn every value into the constraint type. It only guarantees the members listed by the constraint.
function describe<T extends { id: number }>(item: T): string {
return `ID: ${item.id}`;
}This function can read id, but it cannot safely read item.name, because the constraint does not require name.
Also, constraining a parameter does not automatically add a value at runtime. The constraint exists for compile-time checking. JavaScript still receives the original value, so callers must pass values that actually match the required structure.
Exercise
What constraint should you add to sizeOf<T>(value: T): number so that the function can return value.size?
Show answer
Use T extends { size: number }, giving the function a guaranteed numeric size property.