Generic Class Properties
What you'll learn: How to add type parameters to classes so their properties can work with different types across different uses of the same class.
The Core Idea
A generic class property is a property whose type isn't fixed when you define the class — instead, it's determined by a type parameter that gets specified when you create an instance. Think of it like a storage box that you label at purchase time with what type of item it will hold: "Box<Books>" or "Box<Tools>". The box design is the same, but the type of contents is customizable.
Without generics, you'd need separate BookBox, ToolBox, ClothingBox classes. With generics, you write one Box<T> class and the property types adapt based on what T is.
Basic Syntax
class Container<T> {
contents: T;
constructor(value: T) {
this.contents = value;
}
}
const numberContainer = new Container<number>(42);
const stringContainer = new Container<string>("hello");
The <T> after the class name declares a type parameter. The property contents has type T, which means its actual type depends on what you specify when creating an instance.
Why This Matters
Generic class properties let you write one class definition that safely handles many different types. Each instance carries its own specific type information:
class Box<T> {
item: T;
constructor(value: T) {
this.item = value;
}
}
const numberBox = new Box<number>(100);
const result = numberBox.item * 2; // TypeScript knows this is number
const stringBox = new Box<string>("test");
const length = stringBox.item.length; // TypeScript knows this is string
Multiple Generic Properties
You can use type parameters across multiple properties:
class Pair<T> {
first: T;
second: T;
constructor(a: T, b: T) {
this.first = a;
this.second = b;
}
}
const coordinates = new Pair<number>(10, 20);
Key Takeaway: Generic class properties make your classes flexible by letting you specify property types per-instance while maintaining full type safety for each property's operations.