Sub topic 6
Constraining Type Parameters with extends
This chapter assumes you can read basic generic functions such as identity<T>, and that you know object types, union types, and interfaces. A bare type parameter accepts any type. That freedom is useful for passing values through, but it stops you from doing anything with the value. A constraint narrows what callers may pass, and in return it lets the function body use the properties the constraint guarantees.
The problem: an unconstrained T knows nothing
Inside a generic function, TypeScript only lets you do what is safe for every possible T. That means almost nothing.
function longestBroken<T>(a: T, b: T): T {
// Error: Property 'length' does not exist on type 'T'.
return a.length >= b.length ? a : b;
}The compiler is right. A caller could pass 10 and 20, and numbers have no length. The fix is to state the requirement in the type parameter list.
Writing a constraint
You add a constraint with extends after the type parameter name.
function longest<T extends { length: number }>(a: T, b: T): T {
return a.length >= b.length ? a : b;
}
const s = longest("abc", "de"); // "abc" | "de" widened to string
const arr = longest([1, 2], [3]); // number[]
// longest(10, 20); // Error: number has no lengthTwo things happen here:
- Inside the body,
Tis treated as having at least{ length: number }, so.lengthtype-checks. - At each call, the compiler checks that the type argument is assignable to the constraint. If it is not, you get an error at the call site.
Here extends means "is assignable to". It does not mean class inheritance. A string, an array, and an object literal like { length: 3, label: "x" } all satisfy the constraint, because each has a numeric length.
The return type keeps the specific type
A common mistake is to write the constraint as the parameter type. Compare these two functions.
function longestLoose(
a: { length: number },
b: { length: number }
): { length: number } {
return a.length >= b.length ? a : b;
}
const x = longestLoose([1, 2], [3]);
// x is { length: number }. The array type is lost.
// x.push(4); // Error: 'push' does not exist
const y = longest([1, 2], [3]);
y.push(4); // OK: y is number[]The generic version records the exact type the caller passed in and returns it. The non-generic version erases it down to the constraint. This is the main reason to prefer a constrained T over a plain supertype when the return value depends on the input.
Note that longest also forces a and b to share one T. This call fails:
// longest([1, 2], "abc");
// Error: Argument of type 'string' is not assignable to parameter of type 'number[]'.TypeScript infers T from the first argument as number[], then finds that "abc" does not fit. If you do want to allow different types, use two type parameters, each with its own constraint.
function longerLength<A extends { length: number }, B extends { length: number }>(
a: A,
b: B
): number {
return Math.max(a.length, b.length);
}
longerLength([1, 2], "abc"); // 3Constraining with interfaces and unions
A constraint can be any type: an interface, a union, a function type, or a class type.
interface Identifiable {
id: number;
}
function indexById<T extends Identifiable>(items: T[]): Map<number, T> {
const map = new Map<number, T>();
for (const item of items) {
map.set(item.id, item);
}
return map;
}
const users = [
{ id: 1, name: "Ada" },
{ id: 2, name: "Grace" },
];
const byId = indexById(users);
// Map<number, { id: number; name: string }>
const ada = byId.get(1);
console.log(ada?.name); // "Ada"The extra name property is not rejected, because { id: number; name: string } is assignable to Identifiable. It is also not lost: T is the full element type, so byId.get(1) still knows about name. If the parameter were typed Identifiable[], you would get Identifiable back and could not read name.
A union works as a constraint too:
function double<T extends number | string>(value: T): [T, T] {
return [value, value];
}
double(5); // [5, 5]
double("hi"); // ["hi", "hi"]
// double(true); // Error: boolean is not assignable to string | numberConstraints that refer to other parameters
One type parameter can constrain another. The standard example uses keyof.
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const user = { id: 1, name: "Ada" };
const name = getProperty(user, "name"); // string
// getProperty(user, "email"); // Error: not a key of userkeyof T is the union of the property names of T. For user, that is "id" | "name". Constraining K to it makes a misspelled key a compile-time error. The return type T[K] looks up the type of that property, so getProperty(user, "id") returns number and getProperty(user, "name") returns string.
Here is how the compiler resolves the call, step by step.
Constraining to a constructor or function type
Constraints also let you accept classes or callbacks while keeping their types.
function create<T>(ctor: new () => T): T {
return new ctor();
}
class Counter {
count = 0;
}
const c = create(Counter); // Counter
console.log(c.count); // 0For callbacks, constrain to a function shape and use its parts:
function callTwice<F extends (...args: any[]) => unknown>(fn: F, ...args: Parameters<F>): ReturnType<F>[] {
return [fn(...args) as ReturnType<F>, fn(...args) as ReturnType<F>];
}
const results = callTwice((a: number, b: number) => a + b, 1, 2); // number[]The any[] in the constraint is deliberate. With unknown[], functions whose parameters have narrower types would not be assignable, because parameter types are checked contravariantly. This is one of the few places where any is the right tool.
Gotchas
Inside the body, T is not the constraint
Within longest, you can read .length, but you cannot return a value that merely matches the constraint. The caller's T might be a narrower type.
function makeEmpty<T extends { length: number }>(): T {
// Error: '{ length: number }' is assignable to the constraint of type 'T',
// but 'T' could be instantiated with a different subtype of the constraint.
return { length: 0 };
}If a caller wrote makeEmpty<string[]>(), the function would have returned a plain object where an array was promised. The compiler rejects this. Fixes are to return something derived from an input of type T, or to drop the type parameter and return the constraint type.
Constraints do not narrow at runtime
Types are erased when the code compiles to JavaScript, so a constraint is only a compile-time check. Data from the network or JSON.parse can still violate it. Validate such data at the boundary.
Constraining a parameter to itself
A parameter cannot be constrained by a type that depends on itself in a circular way, such as T extends T[]. The compiler reports a circularity error. Recursive constraints that go through an object property or an interface, like T extends Comparable<T>, are allowed.
interface Comparable<T> {
compareTo(other: T): number;
}
function maxOf<T extends Comparable<T>>(items: T[]): T | undefined {
let best: T | undefined;
for (const item of items) {
if (best === undefined || item.compareTo(best) > 0) {
best = item;
}
}
return best;
}Extra properties on fresh object literals
When you pass a fresh object literal directly to a parameter whose type is the bare constraint, excess property checks apply. With a generic T, the literal is inferred as its own type, so extra properties are allowed.
function showId(x: Identifiable) {
console.log(x.id);
}
// showId({ id: 1, extra: true }); // Error: excess property
function showIdGeneric<T extends Identifiable>(x: T) {
console.log(x.id);
}
showIdGeneric({ id: 1, extra: true }); // OKChoosing a constraint
| Goal | Constraint style | Column |
|---|---|---|
| Use a property inside the body | `T extends { prop: Type }` | |
| Accept only certain primitives | `T extends string \ | number` |
| Tie a key to an object | `K extends keyof T` | |
| Accept a class constructor | `new () => T` or `new (...args: any[]) => T` | |
| Accept any function | `F extends (...args: any[]) => unknown` |
Keep the constraint as small as the body needs. A narrow constraint such as { length: number } accepts more callers than a named interface with many members.
Exercise
Write a function pluck that takes an array of objects and a key, and returns an array of that property's values. Constrain it so that a misspelled key is a compile error, and so that pluck([{ id: 1, name: "Ada" }], "name") has type string[].
Show answer
function pluck<T, K extends keyof T>(items: T[], key: K): T[K][] { return items.map((item) => item[key]); } const names = pluck([{ id: 1, name: "Ada" }], "name"); // string[] // pluck([{ id: 1, name: "Ada" }], "email"); // Error: not a key. T is inferred from items, K is constrained to keyof T, and T[K][] is the array of values for that key.
Exercise
Why does function makeEmpty<T extends { length: number }>(): T { return { length: 0 }; } fail to compile, even though { length: 0 } satisfies the constraint?
Show answer
The caller chooses T, and T may be a subtype of the constraint, such as string[]. The returned object has only a length property, so it may not be a valid T. The compiler only knows the value is assignable to the constraint, not to every possible T.