Created
May 2, 2018 21:58
-
-
Save rhalff/b3942cb36ad9ea17121ba1f6fcdfec09 to your computer and use it in GitHub Desktop.
Typescript Mixins, using each others methods.
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
| export type Constructor<T = {}> = new(...args: any[]) => T; | |
| export interface FirstMixin { firstMethod: () => void; } | |
| export interface SecondMixin { secondMethod: () => void; } | |
| export interface UsingFirstMixin { useFirstMethod: () => void; } | |
| export interface UsingFirstAndSecondMixin { useFirstAndSecondMethod: () => void; } | |
| export function FirstMixin <T extends Constructor<{}>>(Base: T) { | |
| return class First extends Base implements FirstMixin { | |
| firstMethod() { | |
| console.log('first method.'); | |
| } | |
| }; | |
| } | |
| export function SecondMixin <T extends Constructor<{}>>(Base: T) { | |
| return class Second extends Base implements SecondMixin { | |
| secondMethod() { | |
| console.log('second method.'); | |
| } | |
| }; | |
| } | |
| export function UsingFirstMixin <T extends Constructor<FirstMixin>>(Base: T) { | |
| return class UsingFirst extends Base implements UsingFirstMixin { | |
| useFirstMethod() { | |
| console.log('Using First Method.'); | |
| this.firstMethod(); | |
| } | |
| }; | |
| } | |
| export function UsingFirstAndSecondMixin <T extends Constructor<FirstMixin & SecondMixin>>(Base: T) { | |
| return class UsingFirstAndSecond extends Base implements UsingFirstAndSecondMixin { | |
| useFirstAndSecondMethod() { | |
| console.log('Using First & Second Method.'); | |
| this.firstMethod(); | |
| this.secondMethod(); | |
| } | |
| }; | |
| } | |
| export class MixedUpBase {} | |
| export class MixedUp extends UsingFirstAndSecondMixin(UsingFirstMixin(FirstMixin(SecondMixin(MixedUpBase)))) { | |
| mixed() { | |
| this.firstMethod(); | |
| this.secondMethod(); | |
| this.useFirstMethod(); | |
| this.useFirstAndSecondMethod(); | |
| } | |
| } | |
| const mixedUp = new MixedUp(); | |
| mixedUp.mixed(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment