All stacks / Intents / Check class type Also written as type check class
instanceof and Type Checking JS · Classes & OOP syntax Copy
object instanceof ClassNameexample Copy
class Animal {}
class Dog extends Animal {}
class Cat extends Animal {}
const pet = new Dog();
console.log(pet instanceof Dog);
console.log(pet instanceof Animal);
console.log(pet instanceof Cat); Note Checks the prototype chain. Can be unreliable across iframes or realms. For built-in types, prefer Array.isArray() over instanceof Array.
syntax Copy
if (value instanceof ClassName) { ... }example Copy
class ApiError extends Error {
constructor(public statusCode: number , message: string ) {
super (message);
}
}
class ValidationError extends Error {
constructor(public fields: string [], message: string ) {
super (message);
}
}
function handleError(err: Error) {
if (err instanceof ApiError) {
console.log(`API error ${err.statusCode}: ${err.message}` );
} else if (err instanceof ValidationError) {
console.log(`Invalid fields: ${err.fields.join(", ")}` );
} else {
console.log(`Unknown error: ${err.message}` );
}
}output
// instanceof narrows to the specific class, enabling access to class-specific propertiesNote instanceof checks the prototype chain at runtime. It does not work with interfaces or type aliases (they have no runtime presence). It also fails across different realms (iframes) since each realm has its own constructor.
Related tasks