What if one class could safely handle any type of data without rewriting code?
Why Generic class syntax in Typescript? - Purpose & Use Cases
Imagine you want to create a class that can store different types of data, like numbers, strings, or even custom objects. Without generics, you'd have to write a new class for each type or use a very loose type like any, which can cause mistakes.
Writing separate classes for each data type is slow and repetitive. Using any removes type safety, so you might accidentally mix types and get errors only when running your code, making debugging hard and frustrating.
Generic class syntax lets you write one flexible class that works with any data type while keeping type safety. You tell the class what type to use when creating it, so TypeScript helps catch mistakes early and saves you from writing repetitive code.
class NumberBox { value: number; constructor(value: number) { this.value = value; } } class StringBox { value: string; constructor(value: string) { this.value = value; } }
class Box<T> {
value: T;
constructor(value: T) {
this.value = value;
}
}You can create reusable, type-safe classes that adapt to any data type, making your code cleaner and safer.
Think of a storage box that can hold toys, books, or clothes. Instead of making a new box for each, you make one adjustable box that fits anything you want to store.
Writing separate classes for each type is slow and error-prone.
Generic classes let you write one flexible, reusable class.
This keeps your code safe and easier to maintain.