What if your code could catch mistakes before you even run it?
Why Generic constraints with extends in Typescript? - Purpose & Use Cases
Imagine you want to write a function that works with different types of objects, but only those that have a specific property, like a name. Without any rules, you might accidentally pass objects that don't have that property, causing errors.
Manually checking each object's properties every time is slow and easy to forget. It leads to bugs and crashes because the program tries to use properties that don't exist. This makes your code fragile and hard to maintain.
Generic constraints with extends let you tell TypeScript to only accept types that have certain properties. This way, the compiler helps you catch mistakes early, making your code safer and easier to understand.
function printName(obj: any) {
console.log(obj.name.toUpperCase());
}function printName<T extends { name: string }>(obj: T) {
console.log(obj.name.toUpperCase());
}This lets you write flexible functions that work with many types, while still keeping your code safe and error-free.
For example, you can create a function that accepts any user or product object, as long as it has a name property, so you can display names without worrying about missing data.
Manual checks for properties are slow and error-prone.
extends constraints ensure only suitable types are used.
This makes your code safer, clearer, and more reusable.