Sub topic 5
Generic Classes
A generic class takes one or more type parameters. Each instance then works with a specific type, and the compiler tracks that type through every method. This chapter assumes you can write generic functions, you know how extends constraints work, and you are comfortable with basic class syntax such as fields, constructors, and access modifiers.
From Generic Function to Generic Class
A generic function declares its type parameter on the function. A generic class declares it on the class, and every member of that class can use it. The type is fixed when you create an instance.
class Stack<T> {
private items: T[] = [];
push(item: T): void {
this.items.push(item);
}
pop(): T | undefined {
return this.items.pop();
}
get size(): number {
return this.items.length;
}
}
const names = new Stack<string>();
names.push("Ada");
// names.push(1); // Error: number is not assignable to string
const last = names.pop(); // string | undefinedStack<string> and Stack<number> are different types. They come from one class declaration, and the compiler checks each instance against its own type argument.
Inference at Construction
When the constructor uses T in its parameters, TypeScript infers the type argument from the values you pass. You usually don't need to write it.
class Box<T> {
constructor(public value: T) {}
}
const a = new Box(5); // Box<number>
const b = new Box("hi"); // Box<string>
const c = new Box<string | number>("hi"); // explicit, wider typeInference has no information when the constructor takes no T values. In that case T becomes unknown, unless the class declares a default.
class Stack<T> {
private items: T[] = [];
push(item: T): void {
this.items.push(item);
}
}
const loose = new Stack(); // Stack<unknown>: nothing to infer from
loose.push("anything"); // compiles, but you have lost type safetyThis is the most common way to lose type safety by accident. For classes that start empty, such as stacks, queues, and caches, supply the type argument explicitly.
Where the Type Parameter Is Visible
The type parameter belongs to instances, not to the class itself. That determines where you can use it.
| Location | Can use `T`? | Notes |
|---|---|---|
| Instance fields | Yes | `private items: T[]` |
| Constructor parameters | Yes | Drives inference |
| Instance methods | Yes | Parameters and return types |
| Static members | No | Error: static members cannot reference class type parameters |
| Value positions at runtime | No | `new T()` and `T.name` are not allowed |
A static method that needs generics declares its own type parameter.
class Registry<T> {
private entries = new Map<string, T>();
static create<U>(): Registry<U> {
return new Registry<U>();
}
register(key: string, value: T): this {
this.entries.set(key, value);
return this;
}
get(key: string): T | undefined {
return this.entries.get(key);
}
}
const handlers = Registry.create<() => void>();
handlers.register("start", () => console.log("started"));The reason for the static rule is that there is one class object but many instantiations. A static field would be shared by all of them, so it can't have a type that depends on one particular T.
The register method returns this, so chained calls keep the exact instance type.
Constraints on Class Type Parameters
Constraints work on classes the same way they do on functions. They let the class body rely on properties that every valid T must have.
interface Entity {
id: number;
}
class Repository<T extends Entity> {
private items = new Map<number, T>();
add(item: T): void {
this.items.set(item.id, item);
}
find(id: number): T | undefined {
return this.items.get(id);
}
all(): T[] {
return Array.from(this.items.values());
}
}
interface User extends Entity {
name: string;
}
const users = new Repository<User>();
users.add({ id: 1, name: "Ada" });
const ada = users.find(1); // User | undefined
// new Repository<string>(); // Error: string does not satisfy EntityThe constraint is checked once, where the type argument is supplied. Inside the class, item.id is allowed because T extends Entity. Outside, callers get the full User type back and not just Entity, because T stays as specific as the argument they chose.
Default Type Parameters
A class can give its type parameters defaults. The default applies when the caller omits the type argument and inference has no candidates.
class Cache<K = string, V = unknown> {
private store = new Map<K, V>();
set(key: K, value: V): void {
this.store.set(key, value);
}
get(key: K): V | undefined {
return this.store.get(key);
}
}
const generic = new Cache(); // Cache<string, unknown>
const typed = new Cache<number, string[]>(); // Cache<number, string[]>Parameters with defaults must come after parameters without them. A default can also refer to an earlier parameter, for example class Pair<A, B = A>.
Generic Methods Inside Generic Classes
A method can add its own type parameters on top of the class's. Class parameters are fixed per instance, and method parameters are chosen per call. Use a method parameter when the result type differs from T.
class Collection<T> {
constructor(private items: T[]) {}
map<U>(fn: (item: T) => U): Collection<U> {
return new Collection(this.items.map(fn));
}
filter(predicate: (item: T) => boolean): Collection<T> {
return new Collection(this.items.filter(predicate));
}
toArray(): T[] {
return [...this.items];
}
}
const lengths = new Collection(["a", "bb", "ccc"])
.map((s) => s.length) // Collection<number>
.filter((n) => n > 1)
.toArray(); // number[]filter keeps T, so it needs no extra parameter. map introduces U, and the callback's return type determines it.
Creating Instances of T
Type arguments are erased when the code compiles to JavaScript. At runtime there is no T, so new T() is impossible. If a class needs to produce values, take a factory function or a constructor as a parameter.
class Pool<T> {
private free: T[] = [];
constructor(private create: () => T) {}
acquire(): T {
return this.free.pop() ?? this.create();
}
release(item: T): void {
this.free.push(item);
}
}
const pool = new Pool(() => ({ buffer: new Uint8Array(16) }));
const item = pool.acquire(); // { buffer: Uint8Array }
pool.release(item);
function make<T>(ctor: new () => T): T {
return new ctor();
}
const date = make(Date); // DateErasure has two more consequences. You can't test x instanceof Stack<number>, because only x instanceof Stack exists at runtime. You also can't branch on T with typeof T. If behavior must depend on the type, pass a value that carries the information, such as a factory, a validator, or a string tag.
Structural Typing and Unused Parameters
TypeScript compares classes by structure. If a type parameter never appears in any member, it has no effect on compatibility.
class Tag<T> {
label = "tag";
}
const x: Tag<string> = new Tag<number>(); // compiles: T is never usedThis is a sign that T is doing no work. Either use it in a member or remove it. The same structural comparison applies when T is used. Stack<Dog> is assignable to Stack<Animal> in many cases, because method parameters are checked leniently. That is convenient, but it allows a Cat to be pushed into what is really a stack of dogs. The chapter on variance covers when this is safe.
Common Mistakes
- Constructing an empty generic class without a type argument, which yields
unknown. - Declaring a static field or method that uses the class's
T. - Adding a type parameter that appears in only one place. A plain type is clearer.
- Expecting
Tto exist at runtime fornew T(),instanceof, ortypeof. - Giving a class a constraint that is too narrow, so that useful types are rejected. Constrain to what the class body actually uses.
Exercise
Write a generic class Queue<T> with enqueue(item: T): void, dequeue(): T | undefined, and a size getter. Then explain what type new Queue() produces if you call it with no type argument and no constructor arguments, and how you would avoid that.
Show answer
class Queue<T> { private items: T[] = []; enqueue(item: T): void { this.items.push(item); } dequeue(): T | undefined { return this.items.shift(); } get size(): number { return this.items.length; } }. Calling new Queue() produces Queue<unknown>, because the constructor takes no values to infer T from. Avoid it by writing new Queue<string>() with an explicit type argument, or by giving the class a default such as Queue<T = string>.
Exercise
Why does this code fail to compile, and how do you fix it? class Counter<T> { static seen: T[] = []; }
Show answer
Static members belong to the class object, which is shared by every instantiation, so they can't reference the instance type parameter T. Fix it by removing T from the static member, for example static seen: unknown[] = [], or by giving a static method its own type parameter, such as static create<U>(): Counter<U>.