How do you write a generic class, and how do its type parameters interact with its constructor and methods?
Short answer
Declare the type parameter on the class itself (right after the class name), and it becomes available throughout the entire class body — fields, constructor, and methods can all reference it, and it's fixed to a specific type the moment you instantiate the class with 'new'.
Advertisement
AModel answer
Declare the type parameter on the class itself (right after the class name), and it becomes available throughout the entire class body — fields, constructor, and methods can all reference it, and it's fixed to a specific type the moment you instantiate the class with 'new'.
class Box<T> {
private contents: T;
constructor(value: T) { this.contents = value; }
get(): T { return this.contents; }
set(value: T): void { this.contents = value; }
}
const numberBox = new Box<number>(42);
const stringBox = new Box('hello'); // T inferred as string from the constructor argumentReal-world example
Building a generic Repository<T>, Cache<T>, or Box<T> class reusable across many different entity types with full type safety.
Likely follow-ups
- Can different methods on the same generic class instance introduce their own ADDITIONAL type parameters?
Related topics