Bird
Raised Fist0
Typescriptprogramming~10 mins

Polymorphism through interfaces in Typescript - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Polymorphism through interfaces
Define Interface
↓
Create Classes implementing Interface
↓
Use Interface type variable
↓
Assign different class instances
↓
Call interface method
↓
Run class-specific method implementation
This flow shows how an interface defines a method, classes implement it differently, and a variable of interface type calls the method polymorphically.
Execution Sample
Typescript
interface Animal {
  speak(): string;
}

class Dog implements Animal {
  speak() { return "Woof!"; }
}

class Cat implements Animal {
  speak() { return "Meow!"; }
}

function makeItSpeak(animal: Animal) {
  console.log(animal.speak());
}

makeItSpeak(new Dog());
makeItSpeak(new Cat());
This code shows two classes implementing the same interface and a function calling their speak method polymorphically.
Execution Table
StepActionVariable/InstanceMethod CalledOutput
1Define interface Animal with speak()---
2Define class Dog implementing AnimalDog--
3Define class Cat implementing AnimalCat--
4Call makeItSpeak with new Dog()animal = Dog instancespeak()Woof!
5Call makeItSpeak with new Cat()animal = Cat instancespeak()Meow!
6End of calls---
💡 All calls to makeItSpeak finished, demonstrating polymorphism through interface.
Variable Tracker
VariableStartAfter Step 4After Step 5Final
animalundefinedDog instanceCat instanceundefined
Key Moments - 2 Insights
Why can the same function makeItSpeak accept both Dog and Cat instances?
Because both Dog and Cat implement the Animal interface, makeItSpeak accepts any object that follows that interface, as shown in steps 4 and 5.
How does the program know which speak() method to call?
At runtime, the speak() method of the actual object instance (Dog or Cat) is called, demonstrating polymorphism (see steps 4 and 5 outputs).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the output when makeItSpeak is called with a Dog instance?
A"Woof!"
B"Meow!"
C"Animal speaks"
DNo output
💡 Hint
Check step 4 in the execution_table where Dog's speak() is called.
At which step does the variable 'animal' hold a Cat instance?
AStep 2
BStep 5
CStep 4
DStep 6
💡 Hint
Look at variable_tracker and execution_table rows for step 5.
If a new class Bird implements Animal with speak() returning "Tweet!", what would makeItSpeak(new Bird()) output?
A"Woof!"
B"Meow!"
C"Tweet!"
DError, Bird not recognized
💡 Hint
Polymorphism allows any class implementing Animal to be used, see concept_flow and execution_table.
Concept Snapshot
interface Animal { speak(): string; }
class Dog implements Animal { speak() { return "Woof!"; } }
class Cat implements Animal { speak() { return "Meow!"; } }
function makeItSpeak(animal: Animal) { console.log(animal.speak()); }
makeItSpeak(new Dog()); // Woof!
makeItSpeak(new Cat()); // Meow!

Key: Interface defines method, classes implement differently, function uses interface type to call polymorphically.
Full Transcript
Polymorphism through interfaces means we define a common method in an interface. Classes implement this interface with their own version of the method. A function can accept any object that implements the interface and call the method. At runtime, the correct method for the actual object is called. In the example, Dog and Cat classes implement Animal interface with speak() method. The function makeItSpeak takes an Animal and calls speak(). When called with Dog, it prints Woof!. When called with Cat, it prints Meow!. This shows how one interface type variable can hold different class instances and call their specific methods.

Practice

(1/5)
1. What does polymorphism through interfaces allow in TypeScript?
easy
A. Only one class can implement an interface
B. Different classes to be treated the same if they implement the same interface
C. Interfaces can hold data like variables
D. Classes cannot implement more than one interface

Solution

  1. Step 1: Understand polymorphism concept

    Polymorphism means using different objects in the same way if they share a common interface.
  2. Step 2: Apply to interfaces in TypeScript

    Interfaces define methods that classes promise to implement, allowing different classes to be used interchangeably.
  3. Final Answer:

    Different classes to be treated the same if they implement the same interface -> Option B
  4. Quick Check:

    Polymorphism = Same interface, different classes [OK]
Hint: Polymorphism means same interface, different class objects [OK]
Common Mistakes:
  • Thinking interfaces hold data like variables
  • Believing only one class can implement an interface
  • Assuming classes can't implement multiple interfaces
2. Which of the following is the correct syntax for a TypeScript interface with a method speak() that returns a string?
easy
A. interface Animal { speak(): string; }
B. interface Animal { speak: string(); }
C. interface Animal { speak() => string; }
D. interface Animal { speak: () => string; }

Solution

  1. Step 1: Review interface method syntax

    In TypeScript, methods in interfaces are declared as methodName(): returnType;.
  2. Step 2: Check each option

    interface Animal { speak(): string; } correctly uses speak(): 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.
  3. Final Answer:

    interface Animal { speak(): string; } -> Option A
  4. Quick Check:

    Method syntax = methodName(): returnType [OK]
Hint: Method in interface uses colon after name, not arrow [OK]
Common Mistakes:
  • Using arrow syntax inside interface method
  • Putting parentheses after type instead of method name
  • Confusing function type with method declaration
3. What will be the output of this TypeScript code?
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);
medium
A. Error: area method missing
B. 6 and 12.56
C. 9.00 and 12.57
D. 9 and 12.56

Solution

  1. Step 1: Calculate area of Square

    Square side is 3, so area = 3 * 3 = 9. Output with two decimals is "9.00".
  2. Step 2: Calculate area of Circle

    Circle radius is 2, area = π * 2 * 2 ≈ 12.566. Rounded to two decimals is "12.57".
  3. Final Answer:

    9.00 and 12.57 -> Option C
  4. Quick Check:

    Square area = 9.00, Circle area ≈ 12.57 [OK]
Hint: Calculate areas, then round to 2 decimals [OK]
Common Mistakes:
  • Forgetting to round with toFixed(2)
  • Using wrong formula for circle area
  • Confusing radius and side length
4. Identify the error in this TypeScript code using interfaces and polymorphism:
interface Vehicle {
  move(): void;
}

class Car implements Vehicle {
  move(distance: number) {
    console.log(`Car moved ${distance} meters`);
  }
}

const myCar: Vehicle = new Car();
myCar.move();
medium
A. Missing return type in move method
B. Cannot assign new Car() to Vehicle type
C. Interface Vehicle cannot have methods
D. Method move in Car has a different signature than in Vehicle interface

Solution

  1. Step 1: Compare method signatures

    Interface Vehicle defines move() with no parameters. Car's move method requires a number parameter.
  2. 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.
  3. Final Answer:

    Method move in Car has a different signature than in Vehicle interface -> Option D
  4. Quick Check:

    Method signature mismatch = Error [OK]
Hint: Method signatures must match interface exactly [OK]
Common Mistakes:
  • Thinking parameter difference is allowed
  • Believing assignment to interface type is invalid
  • Ignoring method return type requirements
5. You have an interface 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?
hard
A. function writeLog(logger: Logger, msg: string) { logger.log(msg); }
B. function writeLog(logger: Logger, msg: string) { console.log(msg); }
C. function writeLog(logger: Logger, msg: string) { logger.write(msg); }
D. function writeLog(logger: Logger, msg: string) { logger.log(); }

Solution

  1. Step 1: Understand polymorphism with interfaces

    The function should accept any object implementing Logger and call its log method with the message.
  2. Step 2: Check each function implementation

    function writeLog(logger: Logger, msg: string) { logger.log(msg); } calls logger.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 method write. function writeLog(logger: Logger, msg: string) { logger.log(); } calls log without arguments, which is incorrect.
  3. Final Answer:

    function writeLog(logger: Logger, msg: string) { logger.log(msg); } -> Option A
  4. Quick Check:

    Call interface method with correct argument [OK]
Hint: Call the interface method with the message parameter [OK]
Common Mistakes:
  • Calling wrong method name
  • Not passing the message argument
  • Ignoring the logger parameter
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard