Decorators Metadata
Learn how to use TypeScript decorators to carry extra metadata and extract information about a method at runtime.
We'll cover the following...
The TypeScript compiler includes experimental support for decorators to carry
extra metadata when they are used. This metadata provides us with a little more
information with regard to how a decorator is used. In order to activate this feature,
we will need to set the emitDecoratorMetadata flag in our tsconfig.json file to true as follows:
{"compilerOptions": {// other compiler options"experimentalDecorators": true,"emitDecoratorMetadata": true}}
Let’s now take a closer look at the effect that this compile option has on our generated JavaScript.
Consider the following parameter decorator:
function metadataParameterDec(target: any,methodName: string,parameterIndex: number) {}// Define a class called `ClassWithMetadata`.class ClassWithMetadata {// Define a method called `print`.print(// Apply `metadataParameterDec` decorator on `id` parameter.@metadataParameterDec id: number, name: string) {}}
Here, we have a parameter decorator named metadataParameterDec. This decorator
is being applied to the id parameter of the print method of the ClassWithMetadata class definition on line 11.
If the emitDecoratorMetadata flag of our tsconfig.json file is set to false or is not present, then the compiler will emit the following JavaScript:
function metadataParameterDec(target, methodName, parameterIndex) {}var ClassWithMetadata = /** @class */ (function () {function ClassWithMetadata() {}ClassWithMetadata.prototype.print = function (id, name) {};__decorate([__param(0, metadataParameterDec)], ClassWithMetadata.prototype, "print", null);return ClassWithMetadata;}());
Here, the generated JavaScript defines a standard JavaScript closure for our class
named ClassWithMetadata. The code that is ...