Generic Classes: Constructor and Properties
You'll learn how to create TypeScript classes where the constructor and instance properties use type parameters, enabling type-safe, reusable class designs.
What Are Generic Classes?
Just like generic functions and interfaces, generic classes let you define type parameters that can be used throughout the class body—in constructor parameters, instance properties, and methods. This means you can create a single class blueprint that works safely with many different types.
Think of a generic class like a customizable container: the class defines the container's behavior (how it stores and retrieves items), while the type parameter defines what type of items it holds. Each instance of the class can hold a different type, but each instance is fully type-safe for its chosen type.
Basic Syntax
class Box<T> {
contents: T;
constructor(value: T) {
this.contents = value;
}
}
const numberBox = new Box<number>(42);
const stringBox = new Box<string>("hello");
The <T> after the class name declares the type parameter. It's then used to type both the contents property and the constructor parameter.
Type Inference Works Here Too
const inferredBox = new Box(true); // T inferred as boolean
TypeScript infers T from the constructor argument, just like with generic functions.
Multiple Properties with the Same Type Parameter
class Pair<T> {
first: T;
second: T;
constructor(a: T, b: T) {
this.first = a;
this.second = b;
}
}
const numbers = new Pair(10, 20); // Both must be numbers
All uses of T within the class refer to the same type for that instance.
Key Takeaway: Generic classes use type parameters to make constructors and properties type-safe across different instances, each with its own concrete type.