0
0
Typescriptprogramming~3 mins

Why Generic class syntax in Typescript? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if one class could safely handle any type of data without rewriting code?

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
class NumberBox {
  value: number;
  constructor(value: number) {
    this.value = value;
  }
}

class StringBox {
  value: string;
  constructor(value: string) {
    this.value = value;
  }
}
After
class Box<T> {
  value: T;
  constructor(value: T) {
    this.value = value;
  }
}
What It Enables

You can create reusable, type-safe classes that adapt to any data type, making your code cleaner and safer.

Real Life Example

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.

Key Takeaways

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.