Sub topic 6
Constraining Type Parameters with `extends`
Prerequisites
This chapter assumes you know basic TypeScript types, unions, interfaces, type aliases, functions, and classes. You should also understand that a generic type parameter, such as T, represents a type chosen when code is used.
A generic function can accept many types, but an unconstrained type parameter gives the function no special operations to use safely:
function showLength<T>(value: T): number {
// return value.length; // Error: T might not have length
return 0;
}The type parameter T could be a number, boolean, or object without a length property. TypeScript therefore rejects value.length.
Adding a Constraint
A generic constraint limits which types can replace a type parameter. Write the constraint with extends:
function longest<T extends { length: number }>(a: T, b: T): T {
return a.length >= b.length ? a : b;
}
const word = longest("typescript", "JavaScript");
const numbers = longest([1, 2, 3], [4, 5]);
console.log(word); // typescript
console.log(numbers); // [1, 2, 3]Here, T extends { length: number } means that T must be assignable to an object with a numeric length property. Strings and arrays satisfy this requirement. Numbers do not:
// longest(10, 20); // Error: number does not have lengthThe constraint lets the function body use .length, while the return type still preserves the exact type passed by the caller. The constraint does not mean that T must inherit from a class. It describes the minimum structure that T must provide.
Constraints with Unions
A constraint can also limit a type parameter to a union:
function formatId<T extends string | number>(id: T): string {
return `ID: ${id}`;
}
formatId("user-7"); // OK
formatId(7); // OK
// formatId(true); // ErrorInside the function, TypeScript knows that id is either a string or a number. It does not automatically know which one it is. Use narrowing when the implementation needs type-specific behavior:
function normalizeId<T extends string | number>(id: T): string {
return typeof id === "number" ? id.toString() : id.trim();
}Constraining Keys with `keyof`
The keyof operator produces a union of the property names of a type. Combine it with extends to accept only valid keys:
function getProperty<T, K extends keyof T>(object: T, key: K): T[K] {
return object[key];
}
const user = { id: 1, name: "Ada", active: true };
const name = getProperty(user, "name"); // string
const active = getProperty(user, "active"); // boolean
// getProperty(user, "email"); // Error: email is not a key of userK extends keyof T connects the key argument to the object argument. The indexed access type T[K] then returns the type of that particular property.
Common Errors
A constraint should express the operations your implementation actually needs. This constraint is too narrow if the function only needs to log a value:
function logValue<T>(value: T): void {
console.log(value);
}Adding T extends { length: number } would reject valid values without providing a useful benefit. Also remember that constraints are checked only by TypeScript. They do not validate data received from JSON, network requests, or other JavaScript code at runtime.
Exercise
Write a generic function named first that accepts an array of type T and returns its first element or undefined.
Show answer
function first<T>(items: T[]): T | undefined { return items[0]; }