Skip to content

Instantly share code, notes, and snippets.

@doug
Last active December 4, 2016 21:55
Show Gist options
  • Save doug/d2d3de7a1dc214678e960f2de5c0a380 to your computer and use it in GitHub Desktop.
Save doug/d2d3de7a1dc214678e960f2de5c0a380 to your computer and use it in GitHub Desktop.
Mixins for TypeScript
export interface Empty {}
export interface Class<T> {
new(): T;
}
export type Super = Class<Empty>;
export interface Mixin<M, S> {
<T extends S>(s: Class<T>): Class<T & M>;
}
export function mixin<M>() {
return function<S>(fn: (s: Class<S>) => Class<S & M>): Mixin<M,S> {
return fn;
}
}
export default mixin;
import {mixin, Class, Super} from './mixin';
export class A {
a() {
return 1;
}
}
export interface B {
b(): number;
}
const B = mixin<B>()((s: typeof A) => class extends s implements B {
a() {
return super.a();
}
b() {
console.log(this.a());
return 2;
}
})
export interface C {
c(): number;
}
const C = mixin<C>()((s: Super) => class extends s implements C {
c() {
return 3;
}
})
export interface ABC extends A,B,C {};
// Has proper superclass verification.
export const ABC: Class<ABC> = C(B(A));
export class D extends ABC {
foo() {
console.log(this.a(), this.b(), this.c());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment