0
0
Typescriptprogramming~3 mins

Why instanceof fails on interfaces in Typescript - The Real Reasons

Choose your learning style9 modes available
The Big Idea

Why does <code>instanceof</code> silently fail when checking interfaces, and how can you fix it?

The Scenario

Imagine you want to check if an object follows a certain blueprint (interface) in TypeScript by using instanceof. You try to do this check everywhere in your code manually.

The Problem

But instanceof only works with real classes and their instances, not with interfaces. Interfaces disappear after TypeScript compiles to JavaScript, so instanceof can't find them. This makes your checks fail silently or cause bugs.

The Solution

Instead of instanceof, you use custom type guards or check for specific properties or methods that the interface requires. This way, you reliably know if an object matches the interface without relying on runtime class checks.

Before vs After
Before
if (obj instanceof MyInterface) { /* ... */ }
After
function isMyInterface(obj: any): obj is MyInterface { return obj && 'requiredProp' in obj; }
if (isMyInterface(obj)) { /* ... */ }
What It Enables

This approach lets you safely and clearly verify if objects follow interfaces, avoiding runtime errors and making your code more robust.

Real Life Example

When working with data from an API, you can't use instanceof to check if the data matches your interface. Using type guards, you confirm the data shape before using it, preventing crashes.

Key Takeaways

instanceof only works with classes, not interfaces.

Interfaces vanish after compiling, so runtime checks fail.

Use type guards or property checks to verify interfaces safely.