Constraining to Object Shapes
What you'll learn: How to require that a generic type parameter must have specific properties by constraining it to an object type.
Sometimes a generic function needs to work with any type, as long as that type has certain properties. For example, you might need an object with an id property, or one with both name and age. Generic constraints let you enforce these requirements.
The Problem Without Constraints
Without constraints, TypeScript won't let you access properties on a generic type because it doesn't know if they exist:
function printId<T>(obj: T): void {
console.log(obj.id); // Error: Property 'id' does not exist on type 'T'
}
Constraining with Object Shapes
Use the extends keyword to specify that your type parameter must have certain properties:
function printId<T extends { id: number }>(obj: T): void {
console.log(obj.id); // ✓ OK - TypeScript knows 'id' exists
}
printId({ id: 42, name: "Alice" }); // Works
printId({ name: "Bob" }); // Error: missing 'id'
The constraint T extends { id: number } means "T can be any type, as long as it has an id property of type number."
Multiple Properties
You can require multiple properties in the constraint:
function greet<T extends { name: string; age: number }>(person: T): string {
return `${person.name} is ${person.age} years old`;
}
Key Takeaway: Use extends { propertyName: Type } to constrain a generic type parameter to objects that have specific properties, giving you type-safe access to those properties inside your generic function.