Static Members in Generic Classes
You'll learn: Why static members in generic classes can't use the class's type parameters — and how to work around it.
The Problem
When you define a generic class, you give it type parameters (like T) that apply to instances of that class. But static members belong to the class itself, not to any particular instance. This creates a fundamental conflict: which T would a static member use when there's no instance to tie it to?
Think of it like a factory building. Each product (instance) can have customizable parts (type T). But the factory's main sign outside (a static member) can't say "This factory makes your custom product" — because there's no "your" until someone actually orders one.
How TypeScript Handles This
TypeScript forbids static members from referencing class-level type parameters:
class Box<T> {
static defaultValue: T; // ❌ Error: Static members cannot reference class type parameters
}
Why? Because Box<number> and Box<string> share the same static members. There's only one defaultValue, not one per type argument.
The Workaround
If you need type-aware static behavior, make the static method itself generic:
class Box<T> {
static create<U>(value: U): Box<U> {
return new Box<U>(value);
}
constructor(public value: T) {}
}
const numBox = Box.create(42); // Box<number>
const strBox = Box.create("hello"); // Box<string>
Now the type parameter U belongs to the method, not the class, so each call can have its own type.
Key Takeaway:
Static members in generic classes cannot use the class's type parameters; they exist once for all instances. Make static methods generic instead if you need type-specific behavior.