Extending classes with types in Typescript - Time & Space Complexity
When we extend classes with types in TypeScript, we add new features to existing blueprints. It's important to see how this affects the time it takes for the program to run.
We want to know: how does adding a subclass change the work the program does as it runs?
Analyze the time complexity of the following code snippet.
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
speak() {
return `${this.name} makes a sound.`;
}
}
class Dog extends Animal {
constructor(name: string) {
super(name);
}
speak() {
return `${this.name} barks.`;
}
}
const dogs: Dog[] = [];
for (let i = 0; i < n; i++) {
dogs.push(new Dog(`Dog${i}`));
}
for (const dog of dogs) {
console.log(dog.speak());
}
This code creates a list of dogs by extending the Animal class, then calls a method on each dog.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Loop creating Dog objects and loop calling speak() on each dog.
- How many times: Each loop runs n times, where n is the number of dogs.
As the number of dogs (n) grows, the program does more work creating and speaking for each dog.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 operations (10 creations + 10 speaks) |
| 100 | About 200 operations |
| 1000 | About 2000 operations |
Pattern observation: The total work grows roughly twice as fast as the input size, which means it grows linearly.
Time Complexity: O(n)
This means the time to run the program grows directly in proportion to the number of dogs created and processed.
[X] Wrong: "Extending a class adds extra hidden loops, so the program runs slower than just creating objects."
[OK] Correct: Extending a class only adds new features but does not add extra loops or repeated work by itself. The loops you write control the time, not the extension.
Understanding how class extensions affect time helps you explain your code clearly and shows you know how your program grows with input size. This skill is useful when discussing design and performance.
"What if we added a nested loop inside the speak() method that runs m times? How would the time complexity change?"