0
0
Typescriptprogramming~5 mins

Extending classes with types in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Extending classes with types
O(n)
Understanding Time 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?

Scenario Under Consideration

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

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.
How Execution Grows With Input

As the number of dogs (n) grows, the program does more work creating and speaking for each dog.

Input Size (n)Approx. Operations
10About 20 operations (10 creations + 10 speaks)
100About 200 operations
1000About 2000 operations

Pattern observation: The total work grows roughly twice as fast as the input size, which means it grows linearly.

Final Time Complexity

Time Complexity: O(n)

This means the time to run the program grows directly in proportion to the number of dogs created and processed.

Common Mistake

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

Interview Connect

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.

Self-Check

"What if we added a nested loop inside the speak() method that runs m times? How would the time complexity change?"