0
0
Typescriptprogramming~5 mins

Why instanceof fails on interfaces in Typescript

Choose your learning style9 modes available
Introduction

The instanceof operator checks if an object is created from a specific class, but interfaces do not exist in the final JavaScript code. So, instanceof cannot check interfaces.

You want to check if an object is made from a certain class.
You want to avoid runtime errors by verifying object types.
You want to understand why <code>instanceof</code> does not work with interfaces.
Syntax
Typescript
object instanceof ClassName

instanceof works only with classes or constructor functions.

Interfaces are only used by TypeScript during development and disappear after compiling.

Examples
This checks if pet is created from the Dog class.
Typescript
class Dog {}
const pet = new Dog();
console.log(pet instanceof Dog); // true
This shows that instanceof cannot be used with interfaces because they do not exist at runtime.
Typescript
interface Animal {
  name: string;
}
const pet = { name: 'Buddy' };
// console.log(pet instanceof Animal); // Error: 'Animal' only exists in type space
Sample Program

This program shows that instanceof works with the Dog class but not with the Animal interface.

Typescript
interface Animal {
  name: string;
}

class Dog implements Animal {
  constructor(public name: string) {}
}

const pet = new Dog('Buddy');

console.log(pet instanceof Dog); // true

// The following line would cause an error if uncommented:
// console.log(pet instanceof Animal);
OutputSuccess
Important Notes

Interfaces are only for TypeScript's type checking and do not exist in the JavaScript output.

To check if an object matches an interface, check for the presence of required properties instead.

Use instanceof only with classes or constructor functions.

Summary

instanceof checks if an object is created from a class, not if it matches an interface.

Interfaces disappear after TypeScript compiles to JavaScript, so instanceof cannot see them.

To check interface-like shapes at runtime, check object properties manually.