Implementing interfaces in classes in Typescript - Time & Space Complexity
When a class follows an interface, it must provide certain actions. We want to see how the time to run these actions changes as we use bigger inputs.
How does the work inside these class methods grow when input size grows?
Analyze the time complexity of the following code snippet.
interface Logger {
logMessages(messages: string[]): void;
}
class ConsoleLogger implements Logger {
logMessages(messages: string[]): void {
for (const msg of messages) {
console.log(msg);
}
}
}
This code defines an interface with a method to log messages. The class implements it by printing each message one by one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the array of messages.
- How many times: Once for each message in the input array.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 console logs |
| 100 | 100 console logs |
| 1000 | 1000 console logs |
Pattern observation: The work grows directly with the number of messages. Double the messages, double the work.
Time Complexity: O(n)
This means the time to log messages grows in a straight line with the number of messages.
[X] Wrong: "Implementing an interface makes the code run faster or slower by itself."
[OK] Correct: The interface only sets rules. The speed depends on what the methods actually do, not on the interface itself.
Understanding how your class methods scale with input size shows you can write efficient code that works well as data grows. This skill is useful in many coding tasks.
"What if the logMessages method also called another method inside the class that loops over the messages again? How would the time complexity change?"
Practice
implements keyword do in a TypeScript class?Solution
Step 1: Understand the role of interfaces
Interfaces define a contract of properties and methods that a class must have.Step 2: Role of
Theimplementskeywordimplementskeyword makes sure the class follows that contract exactly.Final Answer:
It ensures the class follows the structure defined by an interface. -> Option AQuick Check:
implementsenforces interface structure [OK]
- Thinking implements creates or imports interfaces
- Believing implements auto-generates code
- Confusing implements with extends
Car implement an interface Vehicle?Solution
Step 1: Identify correct keywords for class and interface
Classes use the keywordimplementsto follow interfaces.Step 2: Check syntax correctness
class Car implements Vehicle {}is the correct way to declare this.Final Answer:
class Car implements Vehicle {} -> Option BQuick Check:
Class uses implements for interfaces [OK]
- Using extends instead of implements for interfaces
- Trying to implement interface in interface declaration
- Using 'uses' keyword which doesn't exist
interface Animal {
name: string;
speak(): string;
}
class Dog implements Animal {
name: string;
constructor(name: string) {
this.name = name;
}
speak() {
return `${this.name} says woof`;
}
}
const dog = new Dog('Buddy');
console.log(dog.speak());Solution
Step 1: Check class implements interface correctly
Dog class has propertynameand methodspeak()as required.Step 2: Understand method output
speak()returns a string with the dog's name and 'says woof'.Final Answer:
"Buddy says woof" -> Option CQuick Check:
Method returns correct string with name [OK]
- Assuming missing method error when method exists
- Confusing property values with method output
- Ignoring string template usage
interface Shape {
area(): number;
}
class Circle implements Shape {
radius: number;
constructor(radius: number) {
this.radius = radius;
}
area(): string {
return (Math.PI * this.radius * this.radius).toFixed(2);
}
}Solution
Step 1: Check interface method signature
InterfaceShaperequiresarea()to return a number.Step 2: Compare with class method return type
Circle'sarea()returns a string becausetoFixed()returns string.Final Answer:
Method area() returns string instead of number. -> Option AQuick Check:
Return type must match interface [OK]
- Returning string when interface expects number
- Forgetting to declare properties
- Using extends instead of implements for interfaces
interface Printer {
print(): void;
}
interface Scanner {
scan(): void;
}How can you create a class
AllInOneMachine that implements both interfaces correctly?Solution
Step 1: Understand multiple interface implementation
TypeScript allows a class to implement multiple interfaces separated by commas.Step 2: Check class methods match all interfaces
Class must have bothprint()andscan()methods.Final Answer:
class AllInOneMachine implements Printer, Scanner { print() { console.log('Printing'); } scan() { console.log('Scanning'); } } -> Option DQuick Check:
Multiple interfaces implemented with comma [OK]
- Using extends instead of implements for interfaces
- Implementing only one interface but adding all methods
- Trying to implement interfaces in interface declaration
Ready to prove it?
Pass the test and this pattern moves unknown
