Implementing Multiple Interfaces

1. Welcome and Icebreaker:

  • If you could have multiple superpowers, which would you choose to combine?

2. Outline the Session:

  • We’ll learn how a class can implement multiple interfaces in TypeScript.
  • Learning Outcomes: Understand how to use multiple interfaces to compose complex types.
  • Let’s combine some powers!

3. Concept Explanation:

  • A class can implement more than one interface, enforcing multiple contracts.
  • Use a comma to separate interfaces in the implements clause.
  • This is useful for composing behaviors from different sources.

4. Live Coding Demonstration:

interface Flyer {
  fly(): void;
}
interface Swimmer {
  swim(): void;
}

class Duck implements Flyer, Swimmer {
  fly() {
    console.log("Duck is flying!");
  }
  swim() {
    console.log("Duck is swimming!");
  }
}

const donald = new Duck();
donald.fly();
donald.swim();

5. Tasks:

  • Short Exercise:
    1. Define two interfaces: Playable (method play()) and Recordable (method record()).
    2. Create a class MediaDevice that implements both interfaces.
    3. Create an instance of MediaDevice and call both methods.