Instanceof

2 snippets across 2 stacks — JavaScript, TypeScript

JSJavaScript

instanceof and Type Checking

JS · Classes & OOP
syntax
object instanceof ClassName
example
class Animal {}
class Dog extends Animal {}
class Cat extends Animal {}

const pet = new Dog();
console.log(pet instanceof Dog);    // true
console.log(pet instanceof Animal); // true
console.log(pet instanceof Cat);    // false

Note Checks the prototype chain. Can be unreliable across iframes or realms. For built-in types, prefer Array.isArray() over instanceof Array.

TSTypeScript

instanceof Guard

TS · Type Guards & Narrowing
syntax
if (value instanceof ClassName) { ... }
example
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 properties

Note 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.