Sub topic 10
Constraining Type Parameters
Assume you know TypeScript generics, object types, union types, and how to compile a .ts file. A generic function can work with many types, but an unconstrained type parameter gives the function no permission to use any specific property or operation. A constraint adds that permission while preserving the connection between the input and output types.
Why constrain a type parameter?
Consider a function that returns the longer of two values:
function longest<T>(a: T, b: T): T {
// Error: Property 'length' does not exist on type 'T'.
return a.length >= b.length ? a : b;
}T might be a string or an array, but it might also be a number. The compiler cannot assume that every possible T has a length property.
Use extends to describe the minimum shape that T must have:
function longest<T extends { length: number }>(a: T, b: T): T {
return a.length >= b.length ? a : b;
}
const text = longest("typescript", "js"); // string
const numbers = longest([1, 2], [1, 2, 3]); // number[]
// longest(10, 20); // Error: number does not satisfy the constraintHere, T extends { length: number } means that callers may use any type assignable to an object with a numeric length. The function returns T, so the result remains related to the arguments instead of becoming a broad object type.
Constraints preserve useful relationships
A constraint can expose a property while still preserving the specific input type:
function first<T extends { [index: number]: string }>(items: T): string {
return items[0];
}
const firstWord = first(["red", "green"]); // stringFor a key-based function, constrain the key separately with keyof. The keyof operator produces a union of the property names of a type.
function getProperty<T, K extends keyof T>(object: T, key: K): T[K] {
return object[key];
}
const user = {
id: 42,
name: "Ada",
active: true
};
const name = getProperty(user, "name"); // string
const id = getProperty(user, "id"); // number
// getProperty(user, "email"); // Error: "email" is not a key of userK extends keyof T prevents invalid keys. The indexed access type T[K] gives the result the type of the selected property.
Common errors and trade-offs
A constraint should state only what the implementation needs. An overly narrow constraint rejects useful callers:
function count<T extends string>(value: T): number {
return value.length;
}This accepts only strings. If the function only needs length, { length: number } is more reusable.
Do not replace a constraint with a type assertion just to silence an error:
function unsafeLength<T>(value: T): number {
return (value as { length: number }).length;
}The assertion tells the compiler to trust you, but it does not check the value at runtime. A constraint checks callers at compile time and documents the function's requirement.
Exercise
Write a generic last function that accepts any array and returns an element of the same element type.
Show answer
function last<T>(items: T[]): T { return items[items.length - 1]; }