Skip to content

Instantly share code, notes, and snippets.

@iamdylanngo
Created April 3, 2019 00:43
Show Gist options
  • Save iamdylanngo/9d640f72d56156811ee3f1a02b16801f to your computer and use it in GitHub Desktop.
Save iamdylanngo/9d640f72d56156811ee3f1a02b16801f to your computer and use it in GitHub Desktop.
mixin-typescript-1.ts
function applyMixins(derivedCtor: any, baseCtors: any[]) {
baseCtors.forEach(baseCtor => {
Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
if (name !== 'constructor') {
derivedCtor.prototype[name] = baseCtor.prototype[name];
}
});
});
}
class Flies {
fly() {
alert('Is it a bird? Is it a plane?');
}
}
class Climbs {
climb() {
alert('My spider-sense is tingling.');
}
}
class Bulletproof {
deflect() {
alert('My wings are a shield of steel.');
}
}
class BeetleGuy implements Climbs, Bulletproof {
climb: () => void;
deflect: () => void;
}
applyMixins (BeetleGuy, [Climbs, Bulletproof]);
class HorseflyWoman implements Climbs, Flies {
climb: () => void;
fly: () => void;
}
applyMixins (HorseflyWoman, [Climbs, Flies]);
var superHero = new HorseflyWoman();
superHero.climb();
superHero.fly();
type Constructor<T = {}> = new (...args: any[]) => T;
function Flies<TBase extends Constructor>(Base: TBase) {
return class extends Base {
fly() {
alert('Is it a bird? Is it a plane?');
}
};
}
function Climbs<TBase extends Constructor>(Base: TBase) {
return class extends Base {
climb() {
alert('My spider-sense is tingling.');
}
};
}
function Bulletproof<TBase extends Constructor>(Base: TBase) {
return class extends Base {
deflect() {
alert('My wings are a shield of steel.');
}
};
}
class Hero {
constructor(private name: string) {
}
}
const BeetleGuy = Climbs(Bulletproof(Hero));
const HorseFlyWoman = Climbs(Flies(Hero));
const superhero = new HorseFlyWoman('Shelley');
superhero.climb();
superhero.fly();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment