Generic Static Methods
What you'll learn: How to define static methods that have their own type parameters, independent of any generic type parameters on the class itself.
The Core Idea
Static methods belong to the class itself, not to instances. When you make a static method generic, its type parameters are determined at the call site — completely separate from any generics the class might have.
Think of it like this: if a class is a factory building, instance methods work with individual products (using the factory's generic type), but static methods are utility functions in the factory office — they can process any type of material you bring them, regardless of what the factory normally produces.
Basic Syntax
class Box<T> {
constructor(public value: T) {}
// Static method with its own generic type parameter U
static create<U>(value: U): Box<U> {
return new Box(value);
}
}
// U is determined at the call site
const numberBox = Box.create(42); // Box<number>
const stringBox = Box.create("hello"); // Box<string>
Notice that U (the static method's type parameter) is independent of T (the class's type parameter). The static method doesn't have access to T — it exists on the class constructor, not on instances.
Why This Matters
Static methods can't use the class's instance-level generics because they don't operate on instances. But they often need to be generic themselves, especially for factory patterns or utility functions that create instances:
class Container<T> {
private items: T[] = [];
// Instance method can use T
add(item: T): void {
this.items.push(item);
}
// Static method needs its own generic
static fromArray<U>(arr: U[]): Container<U> {
const container = new Container<U>();
arr.forEach(item => container.add(item));
return container;
}
}
const words = Container.fromArray(["a", "b", "c"]); // Container<string>
Key Takeaway: Static methods use their own type parameters (like <U>) that are resolved independently at each call site, separate from any class-level generics like <T>.