InstanceType<T> for Constructor Types
What you'll learn: How to extract the type of objects a class or constructor produces without actually creating an instance.
The Problem: Typing Objects Without Instantiation
Sometimes you need to describe the type of object a constructor would create, but you don't have an actual instance handy. For example, you might be writing a factory function, a dependency injection container, or type-checking logic that deals with constructors themselves rather than instances.
You could manually duplicate the class's structure as a type, but that's error-prone and creates maintenance headaches when the class changes.
What InstanceType<T> Does
InstanceType<T> is a utility type that takes a constructor type and extracts the type of the instances it creates.
Think of it like this: If a constructor is a "blueprint machine," InstanceType<T> tells you the shape of what that machine produces, without running the machine.
Syntax
class User {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
type UserInstance = InstanceType<typeof User>;
// UserInstance is { name: string; age: number }
Notice the typeof User — you're passing the constructor function itself as a type, not the instance type.
Why This Matters
When working with constructors as values (common in factories, registries, or dependency injection), you need to type the objects they'll create:
function createInstance<T extends new (...args: any[]) => any>(
constructor: T
): InstanceType<T> {
return new constructor();
}
const user = createInstance(User);
// user is correctly typed as { name: string; age: number }
Key Takeaway: InstanceType<T> extracts the instance type from a constructor type, letting you type objects that will be created by a constructor without needing an actual instance.