If we compare it with the previous decorators we could assume that because the Object.defineProperty() is invoked, the method saySomething will be replaced by the value returned by the __decorated function (like in the method decorator). This assumption is wrong.

If we examine the code snippet above, we will notice that there is a new function named __param.

The __param function is generated by the TypeScript compiler and looks as follows:

The parameter decorator above adds a new property (metadataKey) to the class prototype. The new property is an array and contains the indices of the parameters being decorated. We can consider this new property as metadata.

A parameter decorator is not supposed to modify the behavior of a constructor, method or property. A parameter decorator should only be used to generate some sort of metadata.

Once the metadata has been created we can use another decorator to read it. For example, in the example bellow we can find and updated version of the method decorator that we created in PART II.

The original version logged in console the function name and all its arguments when it was invoked.

The new version reads the metadata to log in console only the parameters that have been decorated using the parameter decorator.

2. Decorator factory

The official TypeScript decorators proposal defines a decorator factory as follows:

A decorator factory is a function that can accept any number of arguments, and must return one of the types of decorator.

We have learned how to implement and consume all the available types of decorator (class, method, property and parameter) but there is something that we can improve. Let’s consider the following code snippet:

We can achieve this by wrapping all the decorators with a decorator factory. The decorator factory is able to identify what type of decorator is required by checking the arguments passed to the decorator: