Limitations of instanceof
You'll learn: Why instanceof isn't a complete solution and where it breaks down in type narrowing.
The Core Problem
While instanceof is powerful for checking class inheritance, it has three major blind spots that can trip you up in real-world TypeScript code.
1. Cross-Context Failures
When objects cross execution boundaries (like iframes in browsers or worker threads), each context has its own separate class constructors. An Array from one iframe isn't instanceof Array from another iframe's perspective, even though it's clearly an array.
Think of it like citizenship: someone might be a valid citizen in their home country, but a different country's border guard won't recognize their passport.
2. Primitives Don't Work
instanceof only works with objects. You cannot use it with primitives:
const num = 5;
// This is always false - primitives aren't instances
if (num instanceof Number) { // false!
// Never executes
}
This is why you use typeof for primitives instead.
3. Interfaces and Structural Types Are Invisible
TypeScript's interfaces and type aliases exist only at compile-time. They disappear completely in JavaScript. Since instanceof runs at runtime, it can't see them:
interface Animal {
name: string;
}
const pet = { name: "Fluffy" };
// Error: 'Animal' only refers to a type, not a value
// if (pet instanceof Animal) { }
For structural types, use the in operator to check for properties instead.
Key Takeaway: instanceof only works for runtime class instances within the same execution context—it fails with primitives, across boundaries, and with TypeScript's compile-time-only types like interfaces.