Typed Object Composition with Typescript and ES7 Decorators

Favor composition over inheritance

I believe (and hope) many of you have read this line recently quite often in the endless stream of posts on the new class keyword implemented in ES2015.

As I personally experienced when working on a medium-sized app, using extend and class with ES6 leads to some many headaches which composition would certainly have avoided.

I won’t go into details about why using composition over inheritance as there’s already many articles around, and they explain it way better than I would — anyway ☺

What I’d like to show you, though, is how you can compose typed objects with decorators using Typescript.

Recommended reading list about composition/inheritance:

Enter Typescript

Typescript is my new favourite toy and I thank Microsoft every working day for creating it (who would have ever said!?). Why Typescript?

  • Typings?
  • ES6/ES7 without massive configurations
  • Great community

You can try Typescript with its official playground.

A simple example of composition

As a simple example, we’re going to create a Todo class which and compose a few different methods (I know, you didn’t expect it).


A real life example with Angular 2

This is a simple example that implements a very basic authorization functionality in a Angular 2 component, based on the value of a User, which we assume we’re getting using the provider UsersProvider.


How many functionalities could you add and reuse to a Angular 2 component using decorators? As you may understand, the possibilities are great. Of course, it’s nothing that was not possible before using different methods, but the elegance and the simplicity with which it’s now possible to write objects makes everything just better (also, why not, thanks to the infamous class keyword).

Unfortunately my imagination didn’t go too far in the examples, but I am sure this can inspire you to come up with much better things.