Generic classes let you write flexible code that works with many types. Constraints make sure the types used have certain features, so your code stays safe and clear.
0
0
Generic class with constraints in Typescript
Introduction
When you want a class to work with different types but need those types to have specific properties or methods.
When you create reusable data structures like containers or wrappers that should only accept certain kinds of objects.
When you want to avoid errors by restricting what types can be used with your generic class.
When you want to write clear code that tells others what kind of types your class expects.
Syntax
Typescript
class ClassName<T extends Constraint> { // class body using T }
T is a placeholder for a type you specify later.
extends Constraint means T must have the features defined by Constraint.
Examples
This class only accepts types that have a
name property.Typescript
interface HasName {
name: string;
}
class PersonHolder<T extends HasName> {
constructor(public person: T) {}
greet() {
console.log(`Hello, ${this.person.name}!`);
}
}This class only accepts
number or string types.Typescript
class Container<T extends number | string> { value: T; constructor(value: T) { this.value = value; } show() { console.log(`Value is: ${this.value}`); } }
Sample Program
This program defines a generic class that only accepts types with a length property. It then creates instances with an array and a string, both of which have length.
Typescript
interface HasLength {
length: number;
}
class LengthPrinter<T extends HasLength> {
constructor(private item: T) {}
printLength() {
console.log(`Length is: ${this.item.length}`);
}
}
const arr = new LengthPrinter([1, 2, 3]);
arr.printLength();
const str = new LengthPrinter('hello');
str.printLength();OutputSuccess
Important Notes
Constraints help catch mistakes early by limiting what types can be used.
You can use interfaces or union types as constraints.
If you try to use a type without the required features, TypeScript will show an error.
Summary
Generic classes let you write flexible, reusable code.
Constraints ensure the generic types have needed properties or methods.
This keeps your code safe and easier to understand.