0
0
Typescriptprogramming~5 mins

Generic constraints with extends in Typescript

Choose your learning style9 modes available
Introduction

Generic constraints with extends help you limit the types that can be used with a generic. This keeps your code safe and clear.

When you want a function to accept only objects with certain properties.
When you want to make sure a generic type has a specific shape or behavior.
When you want to avoid errors by restricting types in reusable code.
When you want to write flexible but safe functions or classes.
Syntax
Typescript
function functionName<T extends ConstraintType>(param: T): void {
  // function body
}

The extends keyword sets a limit on what T can be.

Only types that fit the ConstraintType can be used for T.

Examples
This function accepts any type that has a length property.
Typescript
function printLength<T extends { length: number }>(item: T): void {
  console.log(item.length);
}
This function accepts any object with a name property.
Typescript
interface HasName {
  name: string;
}

function greet<T extends HasName>(person: T): void {
  console.log(`Hello, ${person.name}`);
}
Sample Program

This program defines a function that gets a property value from an object. It uses generic constraints to make sure the key exists on the object.

Typescript
function getProperty<T extends object, K extends keyof T>(obj: T, key: K) {
  return obj[key];
}

const person = { name: 'Alice', age: 30 };

console.log(getProperty(person, 'name'));
console.log(getProperty(person, 'age'));
OutputSuccess
Important Notes

Generic constraints help catch mistakes early by limiting types.

You can use interfaces or types as constraints with extends.

Using keyof with generics helps work safely with object keys.

Summary

Use extends to limit generic types to certain shapes or properties.

This makes your code safer and easier to understand.

Generic constraints work well with interfaces and keyof for objects.