What extends Does in Generic Constraints
You'll learn how extends in a generic context limits what types can be passed as type arguments, preventing invalid operations.
When you write a generic type parameter like <T>, TypeScript allows any type to be passed in. But what if your function needs to access a specific property or method? Without constraints, TypeScript can't guarantee that property exists.
The extends keyword in generic constraints solves this by saying: "This type parameter must be at least this shape."
The Core Idea
Think of extends as a gatekeeper. When you write:
function getLength<T extends { length: number }>(item: T): number {
return item.length;
}
You're telling TypeScript: "T can be any type, as long as it has a length property that's a number."
This means:
- ✅ Strings work (they have
.length) - ✅ Arrays work (they have
.length) - ✅ Objects with a
lengthnumber property work - ❌ Numbers fail (no
.lengthproperty) - ❌ Plain objects without
lengthfail
Why "Extends"?
The word might seem odd, but think of it this way: your type parameter T must extend (or satisfy) the constraint. It must have at least what the constraint requires, but can have more.
getLength("hello"); // ✅ string extends { length: number }
getLength([1, 2, 3]); // ✅ array extends { length: number }
getLength({ length: 10, color: "red" }); // ✅ extra properties are fine
getLength(42); // ❌ number does not extend { length: number }
Key Takeaway: extends in generic constraints enforces that a type parameter must satisfy a minimum structure, enabling type-safe operations inside the generic function or class.