Published on

Mixins and Composition in Typescript Part 2

Authors
Composition with Interfaces in Typescript

Let's look out how to use composition with interfaces in Typescript. In Part 1 we learned how to use Mixins to achieve code reusablity. In Part 2 we will look at how to achieve the same result. But instead of mixins, we will use composition with interfaces.

Composition with Interfaces

We define two interfaces

interface CanFly {
  fly(): void
}

interface CanSwim {
  swim(): void
}

Next we implement two classes that implement these Interfaces

class FlyingAbility implements CanFly {
  fly() {
    console.log('I can fly!')
  }
}

class SwimmingAbility implements CanSwim {
  swim() {
    console.log('I can swim!')
  }
}

Laslty we create a Duck class that implements the previously created interfaces.

class Duck implements CanFly, CanSwim {
  private flyingAbility: CanFly = new FlyingAbility()
  private swimmingAbility: CanSwim = new SwimmingAbility()

  fly() {
    this.flyingAbility.fly()
  }

  swim() {
    this.swimmingAbility.swim()
  }
}

const duck = new Duck()
duck.fly() // Output: I can fly!
duck.swim() // Output: I can swim!

Conclusion

We achieved the same result as in Part 1. But instead of a mixin we used composition with interfaces.