Created
February 22, 2013 22:55
-
-
Save acrees/5017253 to your computer and use it in GitHub Desktop.
Simple TypeScript implementation of mixins.
This file contains hidden or 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
// 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