Guest User

Untitled

a guest
Jan 21st, 2018
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.11 KB | None | 0 0
  1. type Constructor<T> = new(...args: any[]) => T;
  2.  
  3. function mixin<T>(MixIn: Constructor<T>) {
  4. return function decorator<U>(Base: Constructor<U>) : Constructor<T & U> {
  5. Object.getOwnPropertyNames(MixIn.prototype).forEach(name => {
  6. Base.prototype[name] = MixIn.prototype[name];
  7. });
  8.  
  9. return Base as Constructor<T & U>;
  10. }
  11. }
  12.  
  13. class MixInClass {
  14. mixinMethod() {console.log('mixin method is called')}
  15. }
  16.  
  17. /**
  18. * apply mixin(MixInClass) implicitly (use decorator syntax)
  19. */
  20. @mixin(MixInClass)
  21. class Base1 {
  22. baseMethod1() { }
  23. }
  24. const m1 = new Base1();
  25. m1.baseMethod1();
  26. m1.mixinMethod(); // error TS2339: Property 'mixinMethod' does not exist on type 'Base1'.
  27.  
  28. /**
  29. * apply mixin(MixInClass) explicitly
  30. */
  31. class Base2 {
  32. baseMethod2() { }
  33. }
  34. const MixedBase2 = mixin(MixInClass)(Base2);
  35. const m2 = new MixedBase2();
  36. m2.baseMethod2();
  37. m2.mixinMethod(); // OK
  38.  
  39. //...
  40. var Base1 = /** @class */ (function () {
  41. function Base1() {
  42. }
  43. Base1.prototype.baseMethod1 = function () { };
  44. Base1 = __decorate([
  45. mixin(MixInClass)
  46. ], Base1);
  47. return Base1;
  48. }());
  49. //...
Add Comment
Please, Sign In to add comment