Generic constraints
Using `extends` to require a minimum shape from a type parameter, so a generic function can use that shape and still return the caller's exact type.
Why generics, and generic functionsObject types, optional and readonly properties
Generic constraints
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- Inside a generic function, an unconstrained `T` could be anything, so TypeScript only lets you do what is valid for every possible type; reading `.length` on it is an error.
- `T extends { length: number }` sets a lower bound: callers may pass any type that has at least that shape, and inside the function you may use that shape.
- A constraint is different from a plain parameter type: `(a: { length: number })` returns the wide constraint type, while `<T extends { length: number }>(a: T): T` returns the caller's own type, such as `string`.
- Returning a fresh object that only matches the constraint, like `{ id: 0 }` for `T extends { id: number }`, is an error, because `T` might be a subtype with more properties; build the result from the input instead.
- One type parameter can be constrained by another, as in `K extends keyof T`, which ties a key argument to the object argument it must belong to.
- Constraints can be any type, including unions of primitives such as `T extends string | number`.
A type parameter knows nothing by default
The previous lesson wrote generic functions that never touched their values: first returned an element, map handed each one to a callback. Try a function that actually uses its argument and it breaks:
function longest<T>(a: T, b: T): T {
return a.length >= b.length ? a : b;
// Error: Property 'length' does not exist on type 'T'.
}
That error is correct. Inside the body, T could become any type at all, including number, which has no length. The compiler only allows operations that work for every possible T, and with no information that is almost nothing.
What you want to say is: T can be many things, but at least it has a length.
extends sets a minimum
A constraint is written 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 word = longest("apple", "fig"); // string
const list = longest([1, 2], [3]); // number[]
longest(10, 20);
// Error: Argument of type 'number' is not assignable to parameter of type '{ length: number; }'.
Read extends here as “is assignable to”, not as class inheritance. Strings and arrays both have a numeric length, so both are allowed. Numbers don’t, so the call is rejected at the call site, where the mistake was made. Inside the body you can now use length, because every allowed T has it.
Think of a constraint as a job posting’s minimum requirements. It says what every applicant must have. It doesn’t stop applicants from having more, and the employer still gets the actual person, not a copy of the posting.
Why not just type the parameter?
If the function only needs length, why not skip the generic?
function longestPlain(a: { length: number }, b: { length: number }) {
return a.length >= b.length ? a : b;
}
const p = longestPlain("apple", "fig"); // { length: number }
p.toUpperCase();
// Error: Property 'toUpperCase' does not exist on type '{ length: number; }'.
The plain version accepts the same arguments but returns the constraint itself, so the caller loses everything about their value except its length. The generic version returns T, the caller’s own type. That’s the whole point of a constraint: the function relies on a little, and the caller keeps everything.
If the return type doesn’t mention T, you usually don’t need the generic. function size(x: { length: number }): number is simpler and says the same thing.
The subtype trap
A common mistake is building a fresh value that matches the constraint and returning it as T:
function resetIdBad<T extends { id: number }>(obj: T): T {
return { id: 0 };
// Error: '{ id: number; }' is assignable to the constraint of type 'T',
// but 'T' could be instantiated with a different subtype of constraint '{ id: number; }'.
}
The message is long but the idea is short. A caller might pass { id: 4, name: "Ada" }, making T that type, and they were promised that same type back. { id: 0 } has no name. The fix is to build the result from the input so every extra property survives:
function resetId<T extends { id: number }>(obj: T): T {
return { ...obj, id: 0 };
}
const user = resetId({ id: 4, name: "Ada" }); // { id: number; name: string }
Reaching for as T silences the first version, which is sometimes acceptable inside a carefully written utility, but it moves the responsibility from the compiler to you.
Constraining one parameter by another
Constraints can refer to other type parameters. The classic case is a property getter:
function getProp<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const userName = getProp({ id: 1, name: "Ada" }, "name"); // string
getProp({ id: 1, name: "Ada" }, "email");
// Error: Argument of type '"email"' is not assignable to parameter of type '"name" | "id"'.
keyof T means “the union of T’s property names”, and T[K] means “the type of property K on T”. Both get full lessons in the type-level programming group. For now, notice the pattern: K is constrained by T, so the key must belong to the object that was actually passed.
Constraints aren’t limited to object shapes, either. <T extends string | number> accepts strings and numbers, literal types included, and rejects true with a normal assignability error.
About the video
Matt Pocock’s video covers the whole generics topic, and the embed starts at 05:55, where his chapter on constraints on type arguments begins. From there to about 11:23 he covers constraints on generic types and then in functions, including when an as inside a constrained generic is a reasonable trade, which pairs with the subtype trap above. If you keep watching past that point, he moves on to inference with multiple type arguments and defaults, which the rest of this group covers.
Check yourself
Why does `function len<T>(x: T) { return x.length; }` fail to compile?
`T` has no constraint, so the compiler has to allow for it being `number`, `boolean`, or anything else, and most of those types have no `length` property. Only operations valid for every possible `T` are allowed until a constraint narrows what `T` can be.
What do callers gain from `function longest<T extends { length: number }>(a: T, b: T): T` compared to `function longest(a: { length: number }, b: { length: number })`?
The constrained generic returns `T`, so `longest("apple", "fig")` comes back as `string` and string methods work on it. The non-generic version returns `{ length: number }`, and the caller loses everything about the value except its length.
Why is `return { id: 0 };` an error in a function declared `<T extends { id: number }>(obj: T): T`?
`{ id: 0 }` satisfies the constraint, but `T` might be `{ id: number; name: string }` or any other subtype, and the caller was promised a value of that exact type. Returning `{ ...obj, id: 0 }` works because it keeps every property of the input.
What does `K extends keyof T` express in `getProp<T, K extends keyof T>(obj: T, key: K)`?
It constrains the second type parameter by the first: `K` must be one of the keys of whatever object was passed as `obj`. Passing a key that object doesn't have is a compile-time error, and the return type can be the type of that specific property.
Does a constraint change what TypeScript infers for `T`?
It limits what `T` may be, and an argument outside the constraint is rejected, but `T` is still inferred from the arguments as normal. The constraint is also the fallback if there is nothing to infer from.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.