TypeScript InstanceType<T> Utility Type Explained
Learn how InstanceType<T> extracts the instance type from a class constructor. Examples for factory patterns, dependency injection, and generic class utilities.
Detailed Explanation
Understanding InstanceType
InstanceType<T> constructs a type consisting of the instance type of a constructor function in T. Given a class constructor (the typeof ClassName), it returns what new ClassName() would produce.
Syntax
type InstanceType<T extends abstract new (...args: any) => any> =
T extends abstract new (...args: any) => infer R ? R : any;
Basic Example
class Logger {
level: "info" | "warn" | "error" = "info";
log(msg: string): void {
console.log(`[${this.level}] ${msg}`);
}
}
type LoggerInstance = InstanceType<typeof Logger>;
// Result: Logger (the instance type, with level and log)
Practical Pattern: Generic Factory
function createInstance<T extends new (...args: any[]) => any>(
Ctor: T,
...args: ConstructorParameters<T>
): InstanceType<T> {
return new Ctor(...args);
}
class Database {
constructor(public url: string, public port: number) {}
}
const db = createInstance(Database, "localhost", 5432);
// Type: Database (not any)
With Abstract Classes
abstract class Shape {
abstract area(): number;
}
class Circle extends Shape {
constructor(public radius: number) { super(); }
area() { return Math.PI * this.radius ** 2; }
}
type ShapeInstance = InstanceType<typeof Circle>;
// Result: Circle
Practical Pattern: Plugin Registry
const plugins = {
auth: AuthPlugin,
cache: CachePlugin,
logger: LoggerPlugin,
};
type PluginInstances = {
[K in keyof typeof plugins]: InstanceType<typeof plugins[K]>;
};
Use Case
Use InstanceType<T> in factory functions, dependency injection containers, plugin systems, or any generic utility that creates instances of classes dynamically while preserving the instance type.
Try It — TypeScript Utility Types
Related Topics
TypeScript ConstructorParameters<T> Utility Type Explained
Function Types
TypeScript ReturnType<T> Utility Type Explained
Function Types
TypeScript Parameters<T> Utility Type Explained
Function Types
Composing Multiple TypeScript Utility Types
Advanced Patterns
TypeScript Record<K, T> Utility Type Explained
Object Types