0
0
Typescriptprogramming~3 mins

Why Generic constraints with extends in Typescript? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your code could catch mistakes before you even run it?

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
function printName(obj: any) {
  console.log(obj.name.toUpperCase());
}
After
function printName<T extends { name: string }>(obj: T) {
  console.log(obj.name.toUpperCase());
}
What It Enables

This lets you write flexible functions that work with many types, while still keeping your code safe and error-free.

Real Life Example

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.

Key Takeaways

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.