Created
January 6, 2017 08:59
-
-
Save igrek8/418a4499d2cadd59f96c131db59e6caf to your computer and use it in GitHub Desktop.
typescript class mixins
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
import { Mixin } from './mixin'; | |
import { EventEmitter } from 'events'; | |
// Define .h | |
export declare class EventEmittable { | |
protected events: EventEmitter; | |
} | |
// Implement .cpp | |
export const EventEmittableMixin = (mixin: Mixin) => class extends mixin { | |
protected events: EventEmitter; | |
constructor() { | |
super(); | |
this.events = new EventEmitter(); | |
} | |
}; |
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
import { mixin } from './mixin'; | |
import { EventEmittable, EventEmittableMixin } from './event-emittable'; | |
/** | |
* Just like in C language: | |
* 1. Define .h | |
* 2. Implement .cpp | |
* 3. Use | |
*/ | |
// Define | |
export declare interface MyClass extends EventEmittable { }; | |
// Implement | |
export class MyClass extends mixin(EventEmittableMixin) { | |
constructor() { | |
super(); | |
} | |
} |
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
declare class Base { }; | |
export type Mixin = typeof Base; | |
function Mixin(BaseClass: Mixin = class { }) { | |
return (...Mixins: Array<(Base: Mixin) => Mixin>) => { | |
return Mixins.reduce((c, mixin) => mixin(c), BaseClass); | |
}; | |
} | |
export const mixin = Mixin(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This example assumes that you prefer agregation to inheritance in most cases, so that we can always have an option to share code across files.