Decorators are a powerful feature in TypeScript. Decorators in TypeScript allows us to use declarative programming.In Declarative programming we don’t need to specify all the steps to achieve a task.We just specify what we want achieve without explicitly specifying all the steps.
Decorator is what it name means.It is used to decorate a class or a class member.Decorator attaches meta data to the program element it is attached with.So decorator adds information to the program element such as class.
Decorators in TypeScript are very similar to filters in MVC. Both are used for implementing cross cutting concerns.It is also useful to learn about TypeScript decorators if you are planning to learn Angular 2.Since Angular 2 applications uses TypeScript decorators , so learning about decorators will help learn Angular 2.
We can apply decorators to class, property ,method and parameter.So we can have different types of decorators such as a class decorator or method decorator.
Applying a decorator in TypeScript
To specify decorator for a class or method we write the @ character followed by the name decorator.So if we want to apply a decorator called verify to a class called Employee then we can write:
@verify class Employee { name: string; department: string; constructor(name:string, department: string) { this.name = name; this.department = department; } }
To apply multiple decorators to an entity such as class or method we specify all the decorators sequentially
@decorator1 @decorator2 @decorator3 class ClassName
To create a new decorator we need to define a function with the same name as the name of the decorator.This function can accept multiple parameters depending upon the
type of component being decorated.For example to decorate a class we need to specify a single parameter which specifies the constructor.
function verify(target: any) { // decorator logic }
The above is a class decorator.The target argument refers to the class constructor.If we apply the above decorator to a class then the decorator logic will override the constructor logic.It is similar to the action filters in MVC.
Class decorators are useful when working in Angular 2.Angular 2 uses components which are created by using class decorators.
Since target argument refers to class constructor we can call the original constructor from within the decorator function.
Similarly we can create and apply decorators for methods and properties.
Decorators are not specific to TypeScript but rather are a part of ES2016 specification.
Jorge says
Succinct. Thank you. Every other page I opened to get an intro to decorators was cryptic and tiring. This is the one that helped me understand it. Now I’m ready to delve a bit deeper.
Thank you, again.