0
0
Typescriptprogramming~5 mins

Why instanceof fails on interfaces in Typescript - Performance Analysis

Choose your learning style9 modes available
Time Complexity: Why instanceof fails on interfaces
O(n)
Understanding Time Complexity

We want to understand how checking types with instanceof behaves in TypeScript.

Specifically, why using instanceof with interfaces does not work as expected.

Scenario Under Consideration

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 Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The instanceof operator checks the prototype chain of an object.
  • How many times: It performs a chain lookup until it finds a match or reaches the end.
How Execution Grows With Input

Explain the growth pattern intuitively.

Input Size (prototype chain length)Approx. Operations
22 checks
55 checks
1010 checks

Pattern observation: The number of checks grows linearly with the length of the prototype chain.

Final Time Complexity

Time Complexity: O(n)

This means the check takes longer if the prototype chain is longer, growing in a straight line.

Common Mistake

[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.

Interview Connect

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.

Self-Check

"What if we replaced the interface with an abstract class? How would instanceof behave then?"