0
0
Typescriptprogramming~5 mins

instanceof type guards in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: instanceof type guards
O(n)
Understanding Time Complexity

We want to see how checking types with instanceof affects the time a program takes to run.

How does the time grow when we use instanceof in code that handles many objects?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


class Dog { bark() { return "woof"; } }
class Cat { meow() { return "meow"; } }

function speak(animal: Dog | Cat) {
  if (animal instanceof Dog) {
    return animal.bark();
  } else {
    return animal.meow();
  }
}

const animals = [new Dog(), new Cat(), new Dog()];
animals.forEach(a => speak(a));
    

This code checks each animal's type using instanceof and calls the right sound method.

Identify Repeating Operations
  • Primary operation: Looping through the array of animals and checking each with instanceof.
  • How many times: Once for each animal in the array.
How Execution Grows With Input

Each animal requires one instanceof check, so the total checks grow as the number of animals grows.

Input Size (n)Approx. Operations
1010 instanceof checks
100100 instanceof checks
10001000 instanceof checks

Pattern observation: The number of checks grows directly with the number of animals.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line as the number of objects increases.

Common Mistake

[X] Wrong: "Using instanceof is slow and makes the program take forever as the list grows."

[OK] Correct: Each instanceof check is quick and only happens once per item, so the total time grows steadily, not wildly.

Interview Connect

Understanding how type checks like instanceof scale helps you write clear and efficient code that works well even with many objects.

Self-Check

"What if we replaced the array with a nested array of animals and checked types inside nested loops? How would the time complexity change?"