The more I use TypeScript the more I really like it. I’m starting to use the advanced features – and realize how powerful they are. TypeScript decorators are one of those fantastic features that let’s you automate common tasks and apply them in a sort of “meta-programming” fashion.

One of the use-cases I built for a project at work was a class decorator to automate binding a constructor’s parameters as properties on the new object.

Simple Example

Instead of doing this…

class Person {
   private name: string;
   private email: string;

   constructor(name: string, email: string){
      this.name = name;
      this.email = email;
   }
}

…you can do this…

@BindConstructorParametersAsProperties //Or whatever you want to call it ;)
class Person {
   private name: string;
   private email: string;

   constructor(name: string, email: string){}

   public printEmail(){
      console.log("My email is: " + this.email);
   }
}

Notice how the constructor is empty? The decorator will automatically bind the constructor’s parameters onto the class instance as internal properties. In the example above, printEmail() will work as intended.

This utility doesn’t do that much. But it’s better to have many small re-usable utilities than huge monolithic ones – and this is hopefully one you find helpful.

Code

GitHub Gist for the decorator code