×
☰ See All Chapters

TypeScript Decorators

  1. Decorators make it possible to alter the characteristics of classes, methods, properties, and parameters. They play an important role in Angular, which uses parameter decorators as part of its dependency injection process. 

  2. Decorators allow us to inject code into the actual definition of a class. 

  3. Decorators can be used on class definitions, class properties, class functions, and even method parameters. 

  4. Decorators are an experimental feature of the TypeScript compiler, and have been proposed as part of the ECMAScript 7 standard. TypeScript, however, allows for the use of decorators in ES3 and above. 

  5. In order to use decorators, a new compile option needs to be added to the tsconfig.json file in the root of your project directory. This option is named experimentalDecorators, and needs to be set to true, as follows: 

{

        "compilerOptions": {

                "module": "commonjs",

                "target": "es3",

                "sourceMap": true,

                "experimentalDecorators": true

        },

        "exclude": [

                "node_modules"

        ]

}

  1. A decorator is simply a function which is called with a specific set of parameters. 

  2. It belongs to one of four function types: PropertyDecorator, ClassDecorator, MethodDecorator, or ParameterDecorator. 

  3. Decorator functions are invoked by preceding a Property, Class, Method with the decorator function's name preceded by @. 

  4. Decorators are read by the compiler, which modifies the affected code as it generates JavaScript. In other words, the code in a decorator function executes at runtime, but the code modification is performed during compilation. 

  5. Decorators are not allowed on constructors. 

 

Class Decorators

Property Decorators

Method Decorators

Decorator Factories

Multiple Decorators

 

 

 


All Chapters
Author