Generic Constraints
What
A generic constraint allows you to limit a type parameter to only allow types that satisfy a specific interface or structure.
How
You use the extends keyword within the generic definition:
interface HasId { id: string; }
function logId<T extends HasId>(item: T) {
console.log(item.id); // Safe because T must have an id
}
Why
Standard generics are completely “blind” to the properties of the type they are using. If you need your generic function to access a specific property (like an id or a length), you must use a constraint to tell the compiler that the type T is guaranteed to have those properties.
Summary
Constraints allow you to write generic code that is also aware of specific structural requirements.