Inference in Generic Class Instantiation
What you'll learn: How TypeScript infers type arguments when you create instances of generic classes using new.
The Core Idea
When you instantiate a generic class with the new keyword, TypeScript doesn't always require you to specify the type arguments explicitly. If the constructor accepts arguments, TypeScript can infer the type parameters from those arguments — just like it does with generic functions.
Think of it like ordering a custom drink: if you hand the barista specific ingredients (constructor arguments), they can figure out what kind of drink you want without you having to spell it out.
How It Works
When you call new GenericClass(someValue), TypeScript looks at:
- The type of
someValue - The constructor's parameter types
- How the type parameters flow through the constructor
If the type parameter T appears in a constructor parameter, TypeScript infers T from the argument you pass.
When Inference Succeeds
class Box<T> {
constructor(public value: T) {}
}
// T inferred as number from argument 42
const numBox = new Box(42);
// T inferred as string from argument "hello"
const strBox = new Box("hello");
When You Need Explicit Type Arguments
If the constructor doesn't use the type parameter, or you're passing no arguments, inference has nothing to work with:
class EmptyBox<T> {
private items: T[] = [];
}
// Error: Type argument required
// const box = new EmptyBox();
// Must specify explicitly
const box = new EmptyBox<string>();
Key Takeaway: TypeScript infers type arguments during class instantiation when constructor parameters provide clues about the generic types — otherwise, you must specify them explicitly with angle brackets.