Real-World Use Cases for extends
What you'll learn: How extends in generic constraints solves practical problems like filtering arrays, merging objects, and enforcing minimum shapes.
Now that you understand how extends constrains generic types, let's see where this power actually shines in real-world code.
Filtering Arrays by Type
When filtering arrays, you often want to ensure the returned elements match a specific shape:
function filterByStatus<T extends { status: string }>(
items: T[],
status: string
): T[] {
return items.filter(item => item.status === status);
}
// Works with any object that HAS a status property
const orders = [
{ id: 1, status: 'pending', amount: 100 },
{ id: 2, status: 'shipped', amount: 200 }
];
const pending = filterByStatus(orders, 'pending');
// Type: { id: number; status: string; amount: number }[]
The constraint T extends { status: string } ensures you can safely access .status while preserving all other properties.
Merging Objects Safely
When combining objects, constraints ensure both inputs are actually objects:
function merge<T extends object, U extends object>(obj1: T, obj2: U): T & U {
return { ...obj1, ...obj2 };
}
const user = { name: 'Alice' };
const settings = { theme: 'dark' };
const combined = merge(user, settings);
// Type: { name: string } & { theme: string }
Without extends object, someone could pass primitives, causing runtime errors.
Enforcing Minimum Shapes
Constraints define "at least these properties" without limiting additional ones:
function logEntity<T extends { id: number; createdAt: Date }>(entity: T): void {
console.log(`Entity ${entity.id} created at ${entity.createdAt}`);
}
// Accepts anything WITH id and createdAt, plus extra properties
logEntity({ id: 5, createdAt: new Date(), name: 'Widget', price: 29.99 });
This pattern is common in logging, serialization, and validation utilities.
Key Takeaway: Use extends to create flexible, reusable functions that guarantee minimum requirements while accepting richer data structures—perfect for filtering, merging, and processing objects with known properties.