Why does <code>instanceof</code> silently fail when checking interfaces, and how can you fix it?
Why instanceof fails on interfaces in Typescript - The Real Reasons
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.
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.
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.
if (obj instanceof MyInterface) { /* ... */ }function isMyInterface(obj: any): obj is MyInterface { return obj && 'requiredProp' in obj; }
if (isMyInterface(obj)) { /* ... */ }This approach lets you safely and clearly verify if objects follow interfaces, avoiding runtime errors and making your code more robust.
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.
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.