Generic classes let you create flexible blueprints that work with many types, not just one. This helps you reuse code easily.
Generic class syntax in Typescript
class ClassName<T> { property: T; constructor(value: T) { this.property = value; } method(): T { return this.property; } }
The <T> after the class name means this class uses a generic type called T.
You can use T inside the class to represent any type given when creating an object.
Box holds one item of any type and returns it.class Box<T> { content: T; constructor(value: T) { this.content = value; } getContent(): T { return this.content; } }
const numberBox = new Box<number>(123); const stringBox = new Box<string>("hello");
T and U to hold two different types of values.class Pair<T, U> { first: T; second: U; constructor(first: T, second: U) { this.first = first; this.second = second; } }
This program creates a generic Storage class that can store items of any type. We make one storage for numbers and one for strings, add items, and print them.
class Storage<T> { private items: T[] = []; add(item: T): void { this.items.push(item); } getAll(): T[] { return this.items; } } const numberStorage = new Storage<number>(); numberStorage.add(10); numberStorage.add(20); console.log(numberStorage.getAll()); const stringStorage = new Storage<string>(); stringStorage.add("apple"); stringStorage.add("banana"); console.log(stringStorage.getAll());
You can use any name instead of T, but T is common and means 'Type'.
Generic classes help catch type errors early because TypeScript knows what type you expect.
You can have multiple generic types separated by commas, like <T, U>.
Generic classes let you write flexible, reusable code that works with many types.
Use <T> after the class name to declare a generic type.
Generic types keep your code safe and clear by knowing what type is used.