Polymorphism through interfaces in Typescript - Time & Space Complexity
We want to understand how the time it takes to run code changes when using polymorphism with interfaces.
Specifically, how does calling methods through interfaces affect the number of steps the program takes?
Analyze the time complexity of the following code snippet.
interface Shape {
area(): number;
}
class Circle implements Shape {
constructor(private radius: number) {}
area() { return Math.PI * this.radius * this.radius; }
}
function totalArea(shapes: Shape[]): number {
let sum = 0;
for (const shape of shapes) {
sum += shape.area();
}
return sum;
}
This code calculates the total area of many shapes by calling the area method on each shape through an interface.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the array of shapes and calling
area()on each. - How many times: Once for each shape in the input array.
Each shape requires one call to area(), so the total steps grow as the number of shapes grows.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 calls to area() |
| 100 | 100 calls to area() |
| 1000 | 1000 calls to area() |
Pattern observation: The number of operations grows directly with the number of shapes.
Time Complexity: O(n)
This means the time to compute total area grows in a straight line with the number of shapes.
[X] Wrong: "Calling methods through interfaces makes the code slower in a way that changes the time complexity."
[OK] Correct: Calling methods via interfaces adds a tiny fixed cost per call but does not change how the total steps grow with input size.
Understanding how polymorphism affects time helps you explain your code's efficiency clearly and confidently.
"What if the area() method itself contained a loop over a list of points? How would the time complexity change?"
Practice
Solution
Step 1: Understand polymorphism concept
Polymorphism means using different objects in the same way if they share a common interface.Step 2: Apply to interfaces in TypeScript
Interfaces define methods that classes promise to implement, allowing different classes to be used interchangeably.Final Answer:
Different classes to be treated the same if they implement the same interface -> Option BQuick Check:
Polymorphism = Same interface, different classes [OK]
- Thinking interfaces hold data like variables
- Believing only one class can implement an interface
- Assuming classes can't implement multiple interfaces
speak() that returns a string?Solution
Step 1: Review interface method syntax
In TypeScript, methods in interfaces are declared asmethodName(): returnType;.Step 2: Check each option
interface Animal { speak(): string; } correctly usesspeak(): string;. interface Animal { speak: string(); } incorrectly places parentheses after the type. interface Animal { speak() => string; } uses arrow syntax wrongly. interface Animal { speak: () => string; } uses a function type, which is valid but less common for method declarations.Final Answer:
interface Animal { speak(): string; } -> Option AQuick Check:
Method syntax = methodName(): returnType [OK]
- Using arrow syntax inside interface method
- Putting parentheses after type instead of method name
- Confusing function type with method declaration
interface Shape {
area(): number;
}
class Square implements Shape {
constructor(private side: number) {}
area() { return this.side * this.side; }
}
class Circle implements Shape {
constructor(private radius: number) {}
area() { return Math.PI * this.radius * this.radius; }
}
function printArea(shape: Shape) {
console.log(shape.area().toFixed(2));
}
const sq = new Square(3);
const cir = new Circle(2);
printArea(sq);
printArea(cir);Solution
Step 1: Calculate area of Square
Square side is 3, so area = 3 * 3 = 9. Output with two decimals is "9.00".Step 2: Calculate area of Circle
Circle radius is 2, area = π * 2 * 2 ≈ 12.566. Rounded to two decimals is "12.57".Final Answer:
9.00 and 12.57 -> Option CQuick Check:
Square area = 9.00, Circle area ≈ 12.57 [OK]
- Forgetting to round with toFixed(2)
- Using wrong formula for circle area
- Confusing radius and side length
interface Vehicle {
move(): void;
}
class Car implements Vehicle {
move(distance: number) {
console.log(`Car moved ${distance} meters`);
}
}
const myCar: Vehicle = new Car();
myCar.move();Solution
Step 1: Compare method signatures
Interface Vehicle defines move() with no parameters. Car's move method requires a number parameter.Step 2: Understand TypeScript method compatibility
Method signatures must match exactly for interface implementation. Car's move method does not match Vehicle's move method.Final Answer:
Method move in Car has a different signature than in Vehicle interface -> Option DQuick Check:
Method signature mismatch = Error [OK]
- Thinking parameter difference is allowed
- Believing assignment to interface type is invalid
- Ignoring method return type requirements
Logger with a method log(message: string): void. You want to create two classes: ConsoleLogger that logs to the console, and FileLogger that stores logs in an array. How can you use polymorphism to write a function writeLog(logger: Logger, msg: string) that works with both classes? Which implementation is correct?Solution
Step 1: Understand polymorphism with interfaces
The function should accept any object implementing Logger and call its log method with the message.Step 2: Check each function implementation
function writeLog(logger: Logger, msg: string) { logger.log(msg); } callslogger.log(msg)correctly. function writeLog(logger: Logger, msg: string) { console.log(msg); } ignores the passed logger and logs directly to console. function writeLog(logger: Logger, msg: string) { logger.write(msg); } calls a non-existent methodwrite. function writeLog(logger: Logger, msg: string) { logger.log(); } callslogwithout arguments, which is incorrect.Final Answer:
function writeLog(logger: Logger, msg: string) { logger.log(msg); } -> Option AQuick Check:
Call interface method with correct argument [OK]
- Calling wrong method name
- Not passing the message argument
- Ignoring the logger parameter
Ready to prove it?
Pass the test and this pattern moves unknown
