Skip to content

Instantly share code, notes, and snippets.

@thefill
Created May 7, 2018 17:50
Show Gist options
  • Save thefill/b36f12d0317c8f894c9eb0e13db7cdc0 to your computer and use it in GitHub Desktop.
Save thefill/b36f12d0317c8f894c9eb0e13db7cdc0 to your computer and use it in GitHub Desktop.
Fake multi-inheritance mixin function for TypeScript
///////////
// Code //
/////////
/**
* A little helper for TSC to understand whats going on...
*/
interface Constructor<T> {
new (...args: any[]): T;
}
/**
* Fake multi-inheritance mixin function - perfectly fits into pattern where one compses
* reusable components by combining simpler partial classes. Achieves this by leveraging
* mixin function (inspired by like Scala).
*
* TS understand hybrid class created with this mixin, allows autocomplition & validation.
*/
function mixin<W extends Constructor<{}>, K extends Constructor<{}>>(Base: W, Additive: K, ...additiveArgs: any[]) {
const Premix = class extends Base {
constructor(...args: any[]) {
super(...args);
}
};
const additive = new Additive(...additiveArgs);
Object.keys(additive).forEach(name => {
Premix.prototype[name] = additive[name];
});
return Premix as W & K;
}
///////////
// Test //
/////////
class Lion {
claws = 'sharp';
constructor(...args: any[]) {
this.claws = `${this.claws}, tough`;
}
}
class Scorion {
venom: string;
constructor(...args: any[]) {
this.venom = args[0];
}
}
const Chimera = mixin(Lion, Scorion, 'toxic');
const chimera = new Chimera();
alert(`${chimera.claws} and ${chimera.venom}`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment