Lately I’ve been migrating a JavaScript framework I built (for a work client) over to TypeScript. The core UI components are built using mixins. Using jQuery extend(), the JavaScript code would have done something like:

var TextBox.prototype = $.extend({ ...some object with functions and state....}, CanDoExtraStuff, CanDoOtherCoolStuff);

One of the first things I was hoping TypeScript would allow was to clean this up and make it clearer what was going on.

I ended-up using a combination of the TypeScript doc’s tips on building mixins and decorators.

TypeScript decorators allow you to modify a class / prototype, function, etc. at run-time by adding a nice little annotation in your code. Those using Angular 2 may be familiar with decorators (@Component, etc.). They allow manipulating a class or function in a cleaner and more understandable way than using jQuery extend(), for example. Here’s the code I’m using to build a mixin decorator:

In Your Decorator File

export default function (...mixins: any[]) {
   return function (base) {
      mixins.forEach(mixin => {
         Object.getOwnPropertyNames(mixin.prototype).forEach(name => {
           base.prototype[name] = mixin.prototype[name];
         });
      });
   }
}

In Your Component / Module File

@ApplyMixins(CanDoExtraStuff, CanDoOtherCoolStuff)
export default class TextBox implements CanDoExtraStuff, CanDoOtherCoolStuff {
   ...code...
}