Accessing Properties on Constrained Types
You'll learn: How generic constraints unlock the ability to safely access properties inside generic function bodies.
Without constraints, TypeScript has no idea what properties exist on a generic type parameter. If you write a function like this:
function getProperty<T>(obj: T, key: string) {
return obj[key]; // Error! Can't access arbitrary properties on T
}
TypeScript will complain because T could be anything—a number, a string, or an object with no properties at all.
The Constraint Solution
By constraining T with extends, you tell TypeScript: "I promise T will have certain properties." Now TypeScript allows property access:
function getLength<T extends { length: number }>(item: T): number {
return item.length; // ✓ Safe! We know T has .length
}
getLength("hello"); // 5
getLength([1, 2, 3]); // 3
getLength({ length: 10 }); // 10
Because T extends { length: number }, TypeScript knows every T value must have a length property that's a number. The constraint acts like a contract.
Why This Matters
Without the constraint, you'd get compile-time errors even though your logic is correct. The constraint bridges the gap between "generic flexibility" and "specific property access." It's like telling a function: "You can accept any type of container, as long as it has a handle I can grab."
Key Takeaway: Constraints with extends enable property access in generic functions by guaranteeing those properties exist on the type parameter, turning compile-time errors into safe, type-checked code.