A new feature was introduced in ECMAScript 6—classes. With the introduction of these, the usage of decorators was made possible on the JavaScript engine.
Decorators provide a way to add both annotations and meta-programming syntax to class declarations and its members. As it's in a final state of approval on the TC-39 committee (where TC stands for Technical Committee), the TypeScript compiler already has this available to be used.
To enable it, you can set the flags on the tsconfig.json file:
{
"compilerOptions": {
"target": "ES5",
"experimentalDecorators": true
}
}
Decorators are a special kind of declaration that can be attached to a class, method, accessor property, or parameter. They are used in the form of @expression, where the expression is a function that will be called at runtime.
An example of a decorator that can be applied to a class can be seen in the following code snippet:
function classSeal(constructor: Function) {
Object.seal(constructor);
Object.seal(constructor.prototype);
}
When you create this function, you are saying that the object of the constructor and the prototype of it will be sealed.
To use it inside a class is very simple:
@classSeal
class Animal {
sound: string;
constructor(sound: string) {
this.sound = sound;
}
emitSound() {
return "The animal says, " + this.sound;
}
}
These are just some examples of decorators and their powers to help you with the development of object-oriented programming (OOP) with TypeScript.