What if you could control many different things with just one simple command?
Why Polymorphism through interfaces in Typescript? - Purpose & Use Cases
Imagine you have different types of devices like a phone, a tablet, and a laptop. You want to turn them all on, but each device has its own way to do it. Without a common plan, you have to write separate code for each device every time.
Writing separate code for each device is slow and confusing. If you add a new device, you must change many parts of your program. This makes mistakes easy and your code hard to manage.
Using interfaces, you create a shared plan that all devices follow. This way, you can treat all devices the same way in your code, even if they work differently inside. It keeps your code clean and easy to grow.
phone.turnOn(); tablet.powerUp(); laptop.start();
device.turnOn(); // device can be phone, tablet, or laptopIt lets you write flexible code that works with many different things without changing your main program.
Think of a music app that plays songs from different sources: local files, streaming services, or radio. Using interfaces, the app can play any source without knowing the details.
Interfaces create a common plan for different objects.
Polymorphism lets you use different objects in the same way.
This makes your code easier to write, read, and extend.
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
