×
☰ See All Chapters

TypeScript Decorator factories

In order to allow for decorators to accept parameters, we need to use what is known as a decorator factory. A decorator factory is simply a wrapper function that returns the decorator function itself. As an example of this, consider the following code:

function decoratorFactory(name: string) {

        return function(constructor: Function) {

                console.log(`decorator function called with : ${name}`);

        }

}

We can now use our decorator factory, as follows:

@decoratorFactory('testName')

class ClassWithDecoratorFactory {

}

Note how we can now pass a parameter to the decorator factory, as shown in the usage of @decoratorFactory('testName'). The output of this code is as follows:

decorator function called with : testName

There are a few things to note about decorator factories. Firstly, the decorator function itself will still be called by the JavaScript runtime with automatically populated parameters. Secondly, the decorator factory must return a function definition. Lastly, the parameters defined for the decorator factory can be used within the decorator function itself.

TypeScript Multiple Decorators

Multiple decorators can be applied one after another to the same target. As an example of this, consider the following code:

function firstDecorator(constructor: Function) {

        console.log('firstDecorator called.')

}

 

 

function secondDecorator(constructor: Function) {

        console.log('secondDecorator called.')

}

 

@firstDecorator

@secondDecorator

class ClassWithMultipleDecorators {

}

The output of this code is as follows:

secondDecorator called.

simpleDecorator called.

The output of this code shows us an interesting point about decorators. They are called in reverse order of their definition.


All Chapters
Author