Why instanceof fails on interfaces in Typescript - Performance Analysis
We want to understand how checking types with instanceof behaves in TypeScript.
Specifically, why using instanceof with interfaces does not work as expected.
Analyze the time complexity of the following code snippet.
interface Animal {
name: string;
speak(): void;
}
class Dog implements Animal {
name = 'Dog';
speak() { console.log('Woof'); }
}
const pet = new Dog();
console.log(pet instanceof Dog); // true
console.log(pet instanceof Animal); // Error: 'Animal' only refers to a type, but is being used as a value here.
This code shows that instanceof works with classes but not with interfaces.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
instanceofoperator checks the prototype chain of an object. - How many times: It performs a chain lookup until it finds a match or reaches the end.
Explain the growth pattern intuitively.
| Input Size (prototype chain length) | Approx. Operations |
|---|---|
| 2 | 2 checks |
| 5 | 5 checks |
| 10 | 10 checks |
Pattern observation: The number of checks grows linearly with the length of the prototype chain.
Time Complexity: O(n)
This means the check takes longer if the prototype chain is longer, growing in a straight line.
[X] Wrong: "I can use instanceof to check if an object implements an interface."
[OK] Correct: Interfaces do not exist at runtime, so instanceof cannot check them. It only works with classes that create real objects with prototypes.
Understanding why instanceof works only with classes helps you explain how TypeScript types differ from JavaScript runtime objects.
This skill shows you know the difference between compile-time types and runtime checks.
"What if we replaced the interface with an abstract class? How would instanceof behave then?"