Skip to content

Instantly share code, notes, and snippets.

@acrees
Created February 22, 2013 22:55
Show Gist options
  • Save acrees/5017253 to your computer and use it in GitHub Desktop.
Save acrees/5017253 to your computer and use it in GitHub Desktop.
Simple TypeScript implementation of mixins.
// Base class for any object using mixins.
class Base {
// Member function to include a mixin in this class.
include(target, mixin, includeProperties?: bool) {
for (var name in mixin) {
if (!target.hasOwnProperty(name)) {
if (typeof mixin[name] === "function" || includeProperties) {
target[name] = mixin[name];
}
}
}
}
}
// An interface to describe the contract of the mixin.
interface ILogger {
Log: (text: string) => void;
}
// A class that is our mixin.
class Logger implements ILogger {
Log = (text: string) => {
console.log(text);
}
}
// A class that includes our mixin.
class MyClass extends Base implements ILogger {
constructor() {
super();
// Call this method from super to pull everything in.
this.include(this, new Logger());
}
// Dummy declaration. I know. But it does work.
Log: (text:string) => void;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment