Decorators
Decorators in TypeScript provide a way of programmatically tapping into the process of defining a class. Remember that a class definition describes the shape of a class. In other words, a class definition describes what properties a class has, and what methods it defines. It is only when a class is instantiated, that is, an instance of the class is created, that these properties and methods become available.
Decorators, however, allow us to inject code into the actual definition of a class. Decorators can be used on class definitions, class properties, class functions, and even method parameters. The concept of decorators exists in other programming languages, and are called attributes in C#, or annotations in Java.
In this section, we will explore what decorators are, how they are defined, and how they can be used. We will look at class, property, function, and method decorators.
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. 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": { "target": "es5", "module": "commonjs", "lib": [ "es2015", "dom", ], "strict": true, "esModuleInterop": true, "experimentalDecorators": true, "emitDecoratorMetadata": true, } }
Here, we have specified that the compile options will be using es5 as a target platform, and that we are using the experimentalDecorators and emitDecoratorMetadata options as well. Note that we have also included a lib property, and specified es2015 and dom as library files that the compiler will use. We will experiment with these compiler options in the next chapter.