Sub topic 2
Restricting a Type Parameter with extends
This chapter assumes you can write and call simple generic functions such as identity<T>(x: T): T, and that you know union types, object types, interfaces, and type aliases. You do not need keyof yet. Later chapters cover it.
Why an unconstrained T gets in the way
A type parameter with no restriction can stand for any type. Inside the function body, the compiler therefore lets you do only what is safe for every type, which is almost nothing.
function longest<T>(a: T, b: T): T {
// return a.length >= b.length ? a : b;
// Error: Property 'length' does not exist on type 'T'.
return a;
}The compiler cannot know that T has a length. Someone could call longest(10, 20), and numbers have no such property. Rejecting the body is the compiler protecting that caller.
You have two ways out, and both are worse than a constraint:
- Type the parameters as
any. This compiles, but you lose all checking and the return type. - Type them as
{ length: number }. This checks the members, but the return type becomes{ length: number }, and the caller loses the knowledge that an array went in and an array came out.
A constraint keeps both benefits: the body can use length, and the return type still matches the argument.
The extends 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 arr = longest([1, 2, 3], [1, 2]); // type: number[]
const str = longest("ab", "abc"); // type: "ab" | "abc"
// longest(10, 20); // Error: number has no 'length' propertyThe line T extends { length: number } has two effects.
- Inside the body,
Tis treated as having at least the members of the constraint. That is whya.lengthcompiles. - At each call site, the compiler infers
Tfrom the arguments, then checks the inferred type against the constraint. If it does not fit, the call is an error.
The result arr has type number[], not { length: number }. The constraint sets a minimum requirement. It does not replace the inferred type.
For longest("ab", "abc"), TypeScript infers T as the union of the two string literal types. The call still type-checks, because each literal type is a string, and strings have a length.
What extends means here
In a type parameter list, extends means "is assignable to". It does not mean class inheritance. A type satisfies T extends { length: number } if it is structurally assignable to { length: number }. Arrays, strings, typed arrays, and your own objects with a numeric length all qualify, and none of them has to declare anything about it.
If you leave out the constraint, it is unknown, so <T> is the same as <T extends unknown>. This has been the behavior since TypeScript 3.5. Earlier versions used {}, which is why old code sometimes behaves differently.
How the check happens
The compiler checks a call in a fixed order. It first collects what the arguments say about T. Then it picks a type for T, and last it tests that type against the constraint.
If you pass the type argument yourself, the inference step is skipped and the explicit type goes straight to the constraint test:
function longest<T extends { length: number }>(a: T, b: T): T {
return a.length >= b.length ? a : b;
}
longest<string>("ab", "abc"); // OK
// longest<number>(10, 20); // Error: Type 'number' does not satisfy
// // the constraint '{ length: number; }'.Notice that the two error messages differ. A call that relies on inference reports an argument that is "not assignable to parameter of type". An explicit type argument reports a type that "does not satisfy the constraint". Both mean the same thing, but you will see each in different situations.
Candidates that disagree
Both parameters share one T. If the arguments suggest unrelated types, inference may settle on the first candidate and then reject the second argument:
function longest<T extends { length: number }>(a: T, b: T): T {
return a.length >= b.length ? a : b;
}
// longest([1, 2, 3], "abc");
// Error: Argument of type 'string' is not assignable to parameter of type 'number[]'.Each argument satisfies the constraint on its own. The error comes from sharing T, not from the constraint. If you want mixed arguments, use two type parameters, <A extends Len, B extends Len>, and return A | B.
Constraining to an interface or a type alias
The constraint can be any type. Named types read better than inline object types once they get longer:
interface HasId {
id: number;
}
function indexById<T extends HasId>(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);
console.log(byId.get(1)?.name); // "Ada"The body uses item.id because the constraint guarantees it. The caller gets Map<number, { id: number; name: string }>. A non-generic version, indexById(items: HasId[]): Map<number, HasId>, would make byId.get(1)?.name an error, because name is gone from the type.
You can use the same syntax on classes, interfaces, and type aliases:
class Registry<T extends HasId> {
private items = new Map<number, T>();
add(item: T): void {
this.items.set(item.id, item);
}
get(id: number): T | undefined {
return this.items.get(id);
}
}
const registry = new Registry<{ id: number; label: string }>();
registry.add({ id: 7, label: "seven" });
console.log(registry.get(7)?.label);Several requirements at once
To require more than one thing, use an intersection:
interface HasName {
name: string;
}
function describe<T extends HasId & HasName>(x: T): string {
return `#${x.id} ${x.name}`;
}A type satisfies this only if it has both members.
Constraining to primitives and unions
A constraint can be a union. This is how you say "any of these types":
function wrap<T extends string | number>(value: T) {
return { value };
}
const w = wrap("a"); // type: { value: "a" }This also changes inference. If a constraint includes a primitive type, TypeScript keeps the literal type ("a") when it infers T. Without the constraint it would widen the candidate to string when T appears inside a larger type like { value: T }:
function wrapAny<T>(value: T) {
return { value };
}
const v = wrapAny("a"); // type: { value: string }This is a quiet but useful effect. If you want literal types preserved, add a primitive constraint.
Another common constraint is object, which excludes primitives, or {}, which excludes only null and undefined:
function keys<T extends object>(value: T): string[] {
return Object.keys(value);
}
// keys(5); // Error: number is not assignable to objectPitfall preview: T is not the constraint
Because the body sees T as "something with at least the constraint's members", you can read those members. You cannot create a value and claim it is a T:
function withId<T extends { id: number }>(item: T): T {
// return { id: 0 };
// Error: '{ id: number }' is assignable to the constraint of T,
// but T could be instantiated with a different subtype of the constraint.
return item;
}The caller may have chosen T as { id: number; name: string }, and { id: 0 } is not that type. Return the original item, or a value derived from it that still has type T. A later chapter covers this in detail.
Reading common constraint errors
| Message (shortened) | Usual cause | Fix |
|---|---|---|
| `Property 'x' does not exist on type 'T'` | The body uses a member that `T` does not promise | Add `extends { x: ... }` to `T` |
| `Argument of type 'A' is not assignable to parameter of type 'B'` | The inferred `T` does not satisfy the constraint, or two arguments disagree | Check that the argument has the required members, or use two type parameters |
| `Type 'A' does not satisfy the constraint 'B'` | An explicit type argument fails the constraint | Pass a type that has the required members |
| `... could be instantiated with a different subtype of constraint` | The body returns a new value as `T` | Return the original value, or change the return type |
When a constraint is the wrong tool
A constraint is useful when the return type or another parameter depends on T. If T appears only once, in a parameter, you do not need it:
// The type parameter adds nothing here
function logLength<T extends { length: number }>(x: T): void {
console.log(x.length);
}
// Simpler and equivalent for callers
function logLength2(x: { length: number }): void {
console.log(x.length);
}Use a type parameter when you need to connect types: input to output, one argument to another, or an argument to a callback. The next chapters build on this with keyof, where one type parameter constrains another.
Exercise
This function fails to compile with "Property 'name' does not exist on type 'T'". Fix it so it sorts a copy of any array of objects that have a string name, and returns an array of the same element type.
function sortByName<T>(items: T[]): T[] {
return [...items].sort((a, b) => a.name.localeCompare(b.name));
}
Show answer
Add a constraint that promises the name member:
function sortByName<T extends { name: string }>(items: T[]): T[] {
return [...items].sort((a, b) => a.name.localeCompare(b.name));
}
Calling it with [{ name: "b", age: 1 }, { name: "a", age: 2 }] returns { name: string; age: number }[], so the extra age member is kept in the type.
Exercise
Given function wrap<T extends string | number>(value: T) { return { value }; }, what type does wrap(5) return, and what changes if you remove the constraint?
Show answer
With the constraint, wrap(5) returns { value: 5 }, because a primitive constraint makes TypeScript keep the literal type. Without the constraint, T is widened and the result is { value: number }.
Exercise
Why does longest([1, 2, 3], "abc") fail even though both arguments have a length? Name one way to allow it.
Show answer
Both parameters share a single T, so inference settles on number[] from the first argument and the string is not assignable to it. Declare two type parameters, for example function longest<A extends { length: number }, B extends { length: number }>(a: A, b: B): A | B.