Narrowing with instanceof
Use instanceof to narrow to a specific class within a union.
Syntax
if (value instanceof Date) { }The instanceof operator checks whether an object was created from a particular class. TypeScript uses it to narrow a union of class types to one specific class.
Inside the branch you can safely call methods that belong to that class.
Example
Loading editor…
Press Run to execute the code.
When to use it
- An error handler uses instanceof to distinguish an AxiosError from a generic Error and extract the response body.
- A shape renderer uses instanceof to determine whether to draw a Circle or Rectangle before calling the area method.
- A command processor checks instanceof to route a FileCommand vs a NetworkCommand to the right handler.
More examples
instanceof with class union
Uses instanceof to safely distinguish between Cat and Dog instances and call the correct method on each.
class Cat { meow(): string { return 'Meow'; } }
class Dog { bark(): string { return 'Woof'; } }
function makeSound(pet: Cat | Dog): string {
if (pet instanceof Cat) return pet.meow();
return pet.bark();
}Narrowing error types
Chains instanceof checks from most specific to most general to extract typed fields from different error classes.
class NotFoundError extends Error {
constructor(public resource: string) {
super(`${resource} not found`);
}
}
function handle(err: unknown): string {
if (err instanceof NotFoundError) {
return `Missing: ${err.resource}`;
}
if (err instanceof Error) {
return err.message;
}
return 'Unknown error';
}instanceof with an abstract base
Narrows an abstract base class to its concrete subtypes using instanceof to access subclass-specific properties.
abstract class Shape {
abstract area(): number;
}
class Circle extends Shape {
constructor(public radius: number) { super(); }
area(): number { return Math.PI * this.radius ** 2; }
}
class Square extends Shape {
constructor(public side: number) { super(); }
area(): number { return this.side ** 2; }
}
function describe(s: Shape): string {
if (s instanceof Circle) return `Circle r=${s.radius}`;
if (s instanceof Square) return `Square s=${s.side}`;
return 'Unknown shape';
}
Discussion