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?"
Practice
extends keyword do in TypeScript class definitions?Solution
Step 1: Understand the role of
Theextendsextendskeyword is used to create a new class that inherits from an existing class, gaining its properties and methods.Step 2: Differentiate from other keywords
Other options describe unrelated concepts: interfaces, variables, or modules, which are not whatextendsdoes.Final Answer:
It creates a new class that inherits properties and methods from an existing class. -> Option CQuick Check:
extendsmeans inheritance [OK]
- Confusing extends with interface implementation
- Thinking extends imports modules
- Using extends to declare variables
Animal in TypeScript?Solution
Step 1: Recall correct syntax for class extension
In TypeScript, the keyword to extend a class isextends, so the syntax isclass Dog extends Animal {}.Step 2: Identify incorrect options
inheritsis not a TypeScript keyword,implementsis for interfaces, andimportis for modules.Final Answer:
class Dog extends Animal {} -> Option AQuick Check:
Useextendsto inherit classes [OK]
- Using 'inherits' instead of 'extends'
- Confusing 'implements' with 'extends'
- Trying to import classes inside class declaration
class Person {
name: string;
constructor(name: string) {
this.name = name;
}
greet() {
return `Hello, ${this.name}`;
}
}
class Student extends Person {
constructor(name: string) {
super(name);
}
}
const s = new Student('Anna');
console.log(s.greet());Solution
Step 1: Understand class inheritance and constructor call
TheStudentclass extendsPersonand callssuper(name)in its constructor, so thenameproperty is set correctly.Step 2: Check method call and output
Callings.greet()uses the inherited method, which returnsHello, Anna.Final Answer:
Hello, Anna -> Option BQuick Check:
super() sets parent properties correctly [OK]
- Forgetting to call super() causes errors
- Expecting child's own greet method without override
- Assuming name is undefined without super()
class Vehicle {
wheels: number;
constructor(wheels: number) {
this.wheels = wheels;
}
}
class Car extends Vehicle {
constructor() {
this.wheels = 4;
}
}Solution
Step 1: Check constructor in subclass
TheCarclass constructor assignsthis.wheels = 4but does not callsuper(), which is required before usingthis.Step 2: Understand TypeScript rules for subclass constructors
In TypeScript, a subclass constructor must callsuper()before accessingthis. Missing this causes a compile error.Final Answer:
Missing call to super() in Car constructor -> Option AQuick Check:
Always call super() before this in subclass constructor [OK]
- Assigning to this before super() call
- Forgetting super() call causes runtime error
- Thinking super() is optional in subclass constructor
Employee to add a department property and keep the name property from Person? class Person {
name: string;
constructor(name: string) {
this.name = name;
}
}
class Employee extends Person {
// Add department property here
}Solution
Step 1: Add department property and constructor parameters
To adddepartment, declare it and add it as a parameter in the constructor along withname.Step 2: Call super(name) and assign department
Callsuper(name)to set the inheritednameproperty, then assignthis.department = department.Final Answer:
class Employee extends Person { department: string; constructor(name: string, department: string) { super(name); this.department = department; } } -> Option DQuick Check:
Use super() for parent props and assign new props in constructor [OK]
- Not calling super() in constructor
- Missing department parameter in constructor
- Assigning this.department before super() call
Ready to prove it?
Pass the test and this pattern moves unknown
