The InstanceType type helps you get the type of an object created from a class. It makes it easy to work with instances without repeating code.
0
0
InstanceType type in Typescript
Introduction
When you want to get the type of an object created by a class constructor.
When you want to write functions that accept instances of a class without manually typing the instance shape.
When you want to avoid repeating the instance type and keep your code DRY (Don't Repeat Yourself).
When you want to create variables or parameters that must be instances of a specific class.
Syntax
Typescript
type NewType = InstanceType<typeof ClassName>;ClassName must be a class or constructor function.
typeof ClassName gets the type of the class itself, and InstanceType extracts the instance type.
Examples
This creates a type
DogInstance that matches the type of objects created by Dog.Typescript
class Dog { name: string; constructor(name: string) { this.name = name; } bark() { return `${this.name} says woof!`; } } type DogInstance = InstanceType<typeof Dog>;
This function accepts only instances of the
Dog class.Typescript
function greet(dog: InstanceType<typeof Dog>) { console.log(dog.bark()); }
Sample Program
This program defines a Car class and uses InstanceType to get the type of its instances. The testDrive function accepts only Car instances and calls the drive method.
Typescript
class Car { model: string; constructor(model: string) { this.model = model; } drive() { return `Driving a ${this.model}`; } } type CarInstance = InstanceType<typeof Car>; function testDrive(car: CarInstance) { console.log(car.drive()); } const myCar = new Car('Toyota'); testDrive(myCar);
OutputSuccess
Important Notes
InstanceType only works with class constructors or constructor functions.
If you use it with something that is not a constructor, TypeScript will give an error.
Summary
InstanceType extracts the type of an instance created by a class.
It helps avoid repeating instance types and keeps code clean.
Use it when you want to type variables or parameters as instances of a class.