0
0
Typescriptprogramming~5 mins

Why inheritance needs types in Typescript - Performance Analysis

Choose your learning style9 modes available
Time Complexity: Why inheritance needs types
O(n)
Understanding Time Complexity

When using inheritance in TypeScript, understanding how types affect performance helps us write better code.

We want to see how the program's work grows when inheritance and types interact.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


class Animal {
  speak() {
    return "...";
  }
}

class Dog extends Animal {
  speak() {
    return "Woof!";
  }
}

function makeSpeak(animal: Animal) {
  return animal.speak();
}

const dog = new Dog();
makeSpeak(dog);
    

This code shows a base class and a child class overriding a method, with a function using the base type.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Calling the speak method on an object typed as Animal.
  • How many times: Once per call to makeSpeak, but could be many times if called repeatedly.
How Execution Grows With Input

Explain the growth pattern intuitively.

Input Size (n)Approx. Operations
1010 method calls
100100 method calls
10001000 method calls

Pattern observation: The number of operations grows directly with how many times the method is called.

Final Time Complexity

Time Complexity: O(n)

This means the work grows linearly with the number of method calls on inherited types.

Common Mistake

[X] Wrong: "Inheritance with types makes the program slower because of extra checks."

[OK] Correct: TypeScript types are erased at runtime, so inheritance does not add overhead by itself; the cost depends on how many times methods run.

Interview Connect

Understanding how inheritance and types affect performance helps you explain design choices clearly and write efficient code in real projects.

Self-Check

"What if we changed the method to call another method inside it? How would the time complexity change?"