mixins and merging (multiple extends in typescript)

ref – https://www.digitalocean.com/community/tutorials/typescript-mixins
https://www.typescriptlang.org/docs/handbook/mixins.html#alternative-pattern

Limitations of Classes

Typescript classes can only extend ONE class

Let’s create an example so that we can demonstrate the value of mixins.

Consider two classes, Car and Lorry, which contain the drive and carry methods respectively.
Then, consider a third class called Truck.
A Truck should include both drive and carry methods:

This will not work because we can only extend a single class.

error: Classes can only extend a single class

1) interfaces can extend multiple classes in TypeScript

When an interface extends a class, it extends ONLY the class members but not their implementation because interfaces don’t contain implementations.

2) Declaration merging

When two or more declarations are declared with the same name, TypeScript merges them into one.

By leveraging these two functionalities in TypeScript, we can create an interface with the same name as Truck and extend both the Car and Lorry classes:

Due to declaration merging, the Truck class will be merged with the Truck interface. This means that the Truck class will now contain the function definitions from both Car and Lorry classes.

And here’s how it’s used:

We can now access the methods in Car and Lorry from a truck object.

Full Example