Constraining to Object Shapes
What you'll learn: How to require that generic type parameters have specific properties by constraining them to object types.
When you write generic functions or classes, you often need to work with properties that only exist on certain kinds of objects. Without constraints, TypeScript won't let you access those properties—even if you "know" they'll be there—because the generic type parameter could be anything.
The Problem Without Constraints
If you have a generic function that needs to access a property like .length or .name, TypeScript will throw an error because not all types have those properties. A generic T could be a number, a string, or any other type.
Using Object Shape Constraints
You can constrain a type parameter to have specific properties by using extends with an object type:
function logName<T extends { name: string }>(obj: T): void {
console.log(obj.name); // ✅ TypeScript knows .name exists
}
logName({ name: "Alice", age: 30 }); // Works
logName({ name: "Bob" }); // Works
// logName({ age: 25 }); // ❌ Error: missing 'name'
Here, T extends { name: string } means "T can be any type, as long as it has a name property that's a string."
Why This Matters
This technique lets you write reusable code that works with any object matching a shape, while still guaranteeing type safety. The object can have extra properties—the constraint only requires the minimum shape.
Key Takeaway: Use extends { propertyName: Type } to constrain generic type parameters to objects with specific properties, enabling safe property access while maintaining flexibility.