3.7 Mixins

Mixins is an alternative to inheritance and composition. We can use mixins to create classes combining simpler partial classes.

Getting Ready

All you need to be able to use mixins is an installation of TypeScript.

How to do it…

To create mixins we need to declare the following function somewhere in our code base:

function applyMixins(derivedCtor: any, baseCtors: any[]) {
    baseCtors.forEach(baseCtor => {
        Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
            derivedCtor.prototype[name] = baseCtor.prototype[name];
        });
    });
}

How it works…

Let’s declare to simple classes:

class Climbs {
  climb() {
    alert('My spider-sense is tingling.');
  }
}

class Bulletproof {
  deflect() {
    alert('My wings are a shield of steel.');
  }
}

We can then create classes which include the behavior of the two preceding classes:

class BeetleGuy implements Climbs, Bulletproof {
  climb: () => void;
   deflect: () => void;
}

We can use the applyMixins class to copy the implementation of the two declared methods:

applyMixins(BeetleGuy, [Climbs, Bulletproof]);

Source Code

Mixins


Shiv Kushwaha

Author/Programmer