Decorators in TypeScript

Decorators are a very cool functionality, originally proposed by Google in AtScript (a superset of TypeScript that finally got merged into TypeScript back in early 2015) and also a part of the current standard proposition for ECMAScript 7. In a nutshell, decorators are a way to add metadata to class declarations for use by dependency injection or compilation directives (http://blogs.msdn.com/b/somasegar/archive/2015/03/05/typescript-lt-3-angular.aspx). By creating decorators, we are defining special annotations that may have an impact on the way our classes, methods, or functions behave or just simply altering the data we define in fields or parameters. In that sense, decorators are a powerful way to augment our type's native functionalities without creating subclasses or inheriting from other types.

This is, by far, one of the most interesting features of TypeScript. In fact, it is extensively used in Angular when designing directives and components or managing dependency injection, as we will see from Chapter 5, Enhancing our Components with Pipes and Directives, onwards.

Decorators can be easily recognized by the @ prefix to their name, and they are usually located as standalone statements above the element they decorate, including a method payload or not.

We can define up to four different types of decorators, depending on what element each type is meant to decorate:

  • Class decorators
  • Property decorators
  • Method decorators
  • Parameter decorators

Let's take a look at each of them!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset