TypeScript · Lesson 24 of 42
Generic constraints with extends
Limit what a type parameter accepts with extends so a generic function can safely use properties like length, and learn how constraints affect inference.
UNDERSTAND IT. THEN TRY IT.
What you can do after this lesson
You will be able to say "this generic function works on many types, but only types that have certain things". Without constraints, a generic function knows nothing about T, so it can do almost nothing with it. Constraints give it just enough knowledge to be useful.
The problem
Suppose you want a function that returns the longer of two things, such as strings or arrays. A plain type parameter has no length property to compare:
function longer<T>(a: T, b: T): T {
return a.length >= b.length ? a : b;
}example.ts(2,12): error TS2339: Property 'length' does not exist on type 'T'.
example.ts(2,24): error TS2339: Property 'length' does not exist on type 'T'.The compiler is right: T could be anything, including a number, which has no length. You need to tell it that T must have a length.
extends
Add extends and a type after the type parameter. It means "T can be any type that fits this shape":
function longer<T extends { length: number }>(a: T, b: T): T {
return a.length >= b.length ? a : b;
}
console.log(longer("apple", "fig"));
console.log(longer([1, 2, 3], [4, 5]));apple
[ 1, 2, 3 ]Strings and arrays both have a numeric length, so both are accepted, and inside the function a.length is allowed. A type that does not fit is rejected at the call:
function longer<T extends { length: number }>(a: T, b: T): T {
return a.length >= b.length ? a : b;
}
longer(10, 20);example.ts(5,8): error TS2345: Argument of type 'number' is not assignable to parameter of type '{ length: number; }'.This is the heart of a constraint: callers must pass something that satisfies it, and the function body can rely on it.
The result keeps the caller's type
An important detail is that returning T returns the specific type the caller used, not just the constraint. If the function returned { length: number } instead, the caller would lose everything else:
function longer<T extends { length: number }>(a: T, b: T): T {
return a.length >= b.length ? a : b;
}
const result = longer("apple", "fig");
console.log(result.toUpperCase());APPLEresult is a string, not merely something with a length, so string methods work. That is the benefit of a generic over a function typed with the constraint directly.
Constraining to an object shape
Constraints often describe the object a function needs. This function works on any object with an id, and returns the same kind of object:
function findById<T extends { id: number }>(items: T[], id: number): T | undefined {
return items.find(item => item.id === id);
}
const users = [
{ id: 1, name: "Asha" },
{ id: 2, name: "Ben" },
];
const found = findById(users, 2);
console.log(found?.name);BenNotice that found is typed as the user shape, including name, even though the constraint mentions only id. The constraint is a minimum requirement, not a limit on what the object may hold.
Constraining to a union
A constraint can be any type, including a union of primitives. This restricts what callers may pass while still letting the function return the exact type it received:
function show<T extends string | number>(value: T): T {
console.log(`${typeof value}: ${value}`);
return value;
}
const text = show("ab");
const count = show(21);
console.log(text.toUpperCase(), count.toFixed(1));string: ab
number: 21
AB 21.0Anything outside the union is rejected at the call:
function show<T extends string | number>(value: T): T {
return value;
}
show(true);example.ts(5,6): error TS2345: Argument of type 'boolean' is not assignable to parameter of type 'string | number'.Constraints between type parameters
One type parameter can constrain another, which is how you write functions that take an object and a key of that object. The next lesson on keyof builds exactly this, so here is only a taste:
function pickValue<T extends object, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const user = { name: "Asha", age: 30 };
console.log(pickValue(user, "name"), pickValue(user, "age"));Asha 30Here K is limited to the keys of T, and the result is the type of that property. Asking for a key that does not exist is an error at the call.
Choosing a constraint
- If the function body needs to read a property or call a method on the value, constrain
Tto a type that has it. - Keep constraints as small as possible: ask for
{ length: number }, not forstring | unknown[]. A smaller requirement accepts more types. - If you need no members of
T, no constraint is needed.
Common mistakes
Returning the constraint type instead of T. The caller loses their specific type.
Constraining too tightly. A constraint of string[] rejects other things with a length. Ask only for what you use.
Using extends like inheritance. In a type parameter, extends means "is assignable to", not "inherits from".
Forgetting that constraints are checked at the call, not inside. Inside the function you can rely on the constraint, but the caller is who must satisfy it.
Exercise
Write function maxBy<T extends { score: number }>(items: T[]): T | undefined returning the item with the highest score, and test with objects that also have a name. Write function describe<T extends { name: string }>(item: T): string. Try passing objects missing name, and read the error. Finally, write function merge<A extends object, B extends object>(a: A, b: B): A & B.
KNOWLEDGE CHECK
A quick check. You’ve got this.
Try each question. Every answer comes with an explanation.
Ready for the next small win?
Mark the lesson complete when you are ready.