Generic Classes

What

Classes can also be generic, allowing them to manage and operate on different data types while preserving full type safety for their internal state and methods.

How

You add the type parameter after the class name, which then becomes available to all properties and methods within the class:

class Box<T> {
  private content: T;
  constructor(value: T) { this.content = value; }
  get(): T { return this.content; }
}

const numBox = new Box(42); // Box<number>

Why

Generic classes are the standard way to build complex data structures (like repositories, stores, or linked lists) that need to handle different entities. They allow you to define the management logic once and use it for any specific object type, ensuring that you never lose type information when retrieving items from the structure.

Summary

Use generic classes to build robust, reusable blueprints for your application’s data management logic.