Sub topic 10
Constraining type parameters
This chapter assumes you can write a basic generic function such as function identity<T>(x: T): T. It also assumes you know union types and object types. A constraint limits which types a caller may pass for a type parameter. It also tells the compiler what the function body may do with values of that type.
Why an unconstrained parameter is too limited
Inside a generic function, an unconstrained T could be anything. The compiler therefore allows only operations that work on every type.
function lengthOf<T>(x: T): number {
return x.length;
// error: Property 'length' does not exist on type 'T'.
}You could annotate x as string | unknown[], but then the function loses the link between input and output types. A constraint keeps T and also states a minimum shape for it.
The `extends` syntax
You write a constraint with extends inside the angle brackets.
function longest<T extends { length: number }>(a: T, b: T): T {
return a.length >= b.length ? a : b;
}
const s = longest("abc", "de"); // string
const arr = longest([1, 2], [1, 2, 3]); // number[]
// longest(1, 2); // error: Argument of type 'number' is not assignable to parameter of type '{ length: number; }'Here extends means "is assignable to". It does not mean class inheritance. Any type with a numeric length property satisfies the constraint, including strings, arrays, and your own object types. Nothing has to declare that it implements the constraint.
The constraint does two jobs:
- At the call site, the compiler checks the inferred
Tagainst the constraint and reports an error if it does not fit. - Inside the body, the compiler treats
Tas having at least the constraint's members. That is whya.lengthis allowed.
Note that longest("abc", "de") returns string, not the literal type "abc". The constraint { length: number } does not mention any primitive type, so the compiler widens the inferred literal types to string.
Constraints keep the specific type
A common mistake is to replace the type parameter with its constraint. Compare these two signatures.
function firstLongA<T extends { length: number }>(a: T, b: T): T {
return a.length >= b.length ? a : b;
}
function firstLongB(
a: { length: number },
b: { length: number }
): { length: number } {
return a.length >= b.length ? a : b;
}
const x = firstLongA([1, 2], [3]); // number[]
const y = firstLongB([1, 2], [3]); // { length: number }y has lost its array methods, so y.map(...) is an error. The constrained generic keeps the caller's type and only checks the minimum shape.
The reverse mistake is also common. Returning a value that merely satisfies the constraint does not satisfy T.
function minimum<T extends { length: number }>(x: T, min: number): T {
if (x.length >= min) {
return x;
}
// return { length: min };
// error: '{ length: number; }' is assignable to the constraint of type 'T',
// but 'T' could be instantiated with a different subtype of constraint.
return x;
}The caller may have chosen T as string, and { length: min } is not a string. Inside the body you may only return values that the compiler can prove are T.
Constraining one parameter by another with `keyof`
A type parameter may be constrained by another type parameter in the same list. The most useful form uses keyof, which produces the union of an object type's property names.
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const user = { id: 1, name: "Ada" };
const id = getProperty(user, "id"); // number
const name = getProperty(user, "name"); // string
// getProperty(user, "email");
// error: Argument of type '"email"' is not assignable to parameter of type '"id" | "name"'.K is inferred as the literal type "name", because its constraint (keyof T) is made of string literal types. The return type T[K] then looks up the type of that one property. The result is string, not string | number. A signature like (obj: T, key: string): unknown could not express this.
Constraints and literal types
A constraint that includes a primitive type changes inference. The compiler keeps literal types instead of widening them.
function tag<T extends string>(value: T): { tag: T } {
return { tag: value };
}
const t = tag("button"); // { tag: "button" }Without extends string, the same function would infer { tag: string }. This is why K extends keyof T in the previous section gives you "name" and not string. Use a primitive constraint when callers need to pass a specific string or number value, such as an event name or a key.
| Constraint on `T` | Argument `"button"` | Inferred `T` |
|---|---|---|
| None | `{ tag: T }` position | `string` |
| `extends string` | `{ tag: T }` position | `"button"` |
| `extends { length: number }` | `"abc"` | `string` |
Constraining function and tuple types
Constraints also work on function-shaped parameters. A rest parameter must have an array type, so a type parameter used for rest arguments must be constrained to an array.
function callTwice<A extends unknown[], R>(
fn: (...args: A) => R,
...args: A
): [R, R] {
return [fn(...args), fn(...args)];
}
const results = callTwice((a: number, b: number) => a + b, 1, 2); // [number, number]
// callTwice((a: number, b: number) => a + b, 1, "2");
// error: Argument of type 'string' is not assignable to parameter of type 'number'.Without extends unknown[], the compiler reports that a rest parameter must be of an array type. With it, A is inferred as the tuple [a: number, b: number], and the remaining arguments are checked against that tuple.
Several parameters with one type parameter
When the same T appears in two parameters, the compiler picks one candidate from the arguments and checks the others against it.
function longest<T extends { length: number }>(a: T, b: T): T {
return a.length >= b.length ? a : b;
}
// longest("abc", [1, 2]);
// error: Argument of type 'number[]' is not assignable to parameter of type 'string'.Both arguments have a length, so both satisfy the constraint on their own. The failure comes from sharing one T. There are two ways to fix it.
function longest<T extends { length: number }>(a: T, b: T): T {
return a.length >= b.length ? a : b;
}
// Option 1: name the union explicitly. The union satisfies the constraint.
const r1 = longest<string | number[]>("abc", [1, 2]); // string | number[]
// Option 2: use two type parameters when the arguments may differ.
function longestOf<A extends { length: number }, B extends { length: number }>(
a: A,
b: B
): A | B {
return a.length >= b.length ? a : b;
}
const r2 = longestOf("abc", [1, 2]); // string | number[]Prefer option 2 when the parameters are not meant to be the same type. Prefer one shared T when the function really requires them to match.
Common errors and how to read them
- "Property does not exist on type 'T'": the body uses a member that the constraint does not guarantee. Widen the constraint to include that member.
- "Type 'X' does not satisfy the constraint": the call site, or an explicit type argument, supplies a type that lacks a required member. Check the argument, not the function.
- "'T' could be instantiated with a different subtype of constraint": the body returns a value assignable to the constraint but not to
T. Return a value derived from the parameters, or change the return type. - A result that lost its specific type: the signature uses the constraint type where it should use
T. ReturnTinstead. - Over-constraining: a constraint stricter than the body needs, such as
T extends string[]when onlylengthis used, rejects valid callers. Constrain to the smallest shape the body uses.
Exercises
Exercise
What is the return type of getProperty(user, "name") when user is { id: number; name: string } and getProperty is declared as function getProperty<T, K extends keyof T>(obj: T, key: K): T[K]? Why is it not string | number?
Show answer
It is string. K is inferred as the literal type "name", because its constraint keyof T is a union of string literals. The return type T[K] is then T["name"], which is string. A union would appear only if K were inferred as "id" | "name".
Exercise
This function fails to compile. Explain why, and fix the signature so the call pickLonger(["a"], ["b", "c"]) still returns string[].
function pickLonger<T>(a: T, b: T): T {
return a.length >= b.length ? a : b;
}
Show answer
T is unconstrained, so the compiler does not know that a and b have a length property. Add the constraint: function pickLonger<T extends { length: number }>(a: T, b: T): T. T is inferred as string[] from the arguments, so the result keeps that type.