Extracting Instance Types from Constructors
What you'll learn: How to use the InstanceType<T> utility to extract the type of an instance produced by a constructor function, enabling dynamic type extraction from class constructors.
The Problem
Sometimes you have a constructor function (a class) but need to work with the type of instances that constructor produces, not the constructor itself. This is especially common when you're passing constructors around as values, working with factory patterns, or dealing with dynamic class instantiation.
class User {
constructor(
public name: string,
public age: number
) {}
}
// You have the constructor, but need the instance type
function createInstance(Constructor: typeof User) {
// What type is the return value?
return new Constructor("Alice", 30);
}
Understanding InstanceType<T>
InstanceType<T> is a built-in utility type that extracts the instance type from a constructor type. It uses infer internally to pull out what type of object a constructor creates when you call new on it.
The pattern:
type MyInstance = InstanceType<typeof MyClass>;
Note the typeof — you need it because MyClass by itself refers to instances, while typeof MyClass refers to the constructor.
Basic Example
class Product {
constructor(
public id: number,
public name: string,
public price: number
) {}
display() {
return `${this.name}: $${this.price}`;
}
}
// Extract the instance type
type ProductInstance = InstanceType<typeof Product>;
// Now you can use it
const item: ProductInstance = new Product(1, "Laptop", 999);
Real-World Use Case: Generic Factory
function createFactory<T extends new (...args: any[]) => any>(
Constructor: T
) {
return {
create(...args: ConstructorParameters<T>): InstanceType<T> {
return new Constructor(...args);
}
};
}
class Logger {
constructor(public prefix: string) {}
log(message: string) {
console.log(`[${this.prefix}] ${message}`);
}
}
const loggerFactory = createFactory(Logger);
const myLogger = loggerFactory.create("APP"); // Type is Logger
myLogger.log("Started"); // Fully typed!
Here, InstanceType<T> ensures the return type of create() matches whatever instances the constructor produces.
Why It Matters
Think of InstanceType as a "type mirror" — it reflects the instance shape from the constructor blueprint. You're essentially asking TypeScript: "Given this constructor, what shape will objects have when I call new on it?" This maintains type safety when constructors are treated as first-class values.
Key Takeaway: Use InstanceType<typeof Constructor> to extract the type of instances a class constructor produces, enabling type-safe patterns where constructors are passed around as values or used in generic factory functions.