Skip to content

Instantly share code, notes, and snippets.

@igrek8
Created January 6, 2017 08:59
Show Gist options
  • Save igrek8/418a4499d2cadd59f96c131db59e6caf to your computer and use it in GitHub Desktop.
Save igrek8/418a4499d2cadd59f96c131db59e6caf to your computer and use it in GitHub Desktop.
typescript class mixins
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();
}
};
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();
}
}
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();
@igrek8
Copy link
Author

igrek8 commented Jan 6, 2017

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment