Why inheritance needs types in Typescript - Performance Analysis
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.
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 the loops, recursion, array traversals that repeat.
- Primary operation: Calling the
speakmethod on an object typed asAnimal. - How many times: Once per call to
makeSpeak, but could be many times if called repeatedly.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 method calls |
| 100 | 100 method calls |
| 1000 | 1000 method calls |
Pattern observation: The number of operations grows directly with how many times the method is called.
Time Complexity: O(n)
This means the work grows linearly with the number of method calls on inherited types.
[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.
Understanding how inheritance and types affect performance helps you explain design choices clearly and write efficient code in real projects.
"What if we changed the method to call another method inside it? How would the time complexity change?"