Created
May 7, 2018 17:50
-
-
Save thefill/b36f12d0317c8f894c9eb0e13db7cdc0 to your computer and use it in GitHub Desktop.
Fake multi-inheritance mixin function for TypeScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/////////// | |
// 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