You typically won't use decorators that often to have a direct impact on the end users of your page, or the users visiting your page. But instead, decorators are a particularly well-suited instrument for writing code, which is then easier to use by other developers.

Now, to use decorators we have to enable the following in the tsconfig.json file:

Screenshot 2022-11-01 at 9.42.14 PM.png

We need to uncomment it or we won’t be able to use decorators.

Class Decorators

Consider this basic class:

Screenshot 2022-11-01 at 9.44.50 PM.png

Now, we will add decorators to this class.

Decorator in the end is a function. A function you apply to something. For example to a class. The convention is the start the function name with a capital letter. But you can also use small letters.

Screenshot 2022-11-01 at 9.49.41 PM.png

Note: On lines 2-5 we have our decorator. This is a function as discussed earlier.Now, the constructor is passed as the argument if I add this decorator to a class. Note on line 7 this is how we add this decorator to our class using an “@” before the name of the decorator. Now, if I check the console log:

Screenshot 2022-11-01 at 9.51.42 PM.png

Please also note that our decorator output logging and this class or this constructor function log here is printed first before we see creating person object and our person object because indeed decorators execute when your class is defined, not when it is instantiated. You don't need to instantiate your class at all. We could remove that code for instantiating the class and we would still get that decorator output.

Decorator Factories

Now, we can also create decorator factory, which basically returns a decorator function but allows us to configure it when we assign it as a decorator to something. Now, we will convert our Logger decorator to a decorator factory.

Screenshot 2022-11-01 at 10.00.21 PM.png

Here, Logger is the decorator factory which is returning a function which will in turn execute the logic inside. Note on line 9 we are executing Logger as a function using () in front of it.

Now, we can customize it like:

Screenshot 2022-11-01 at 10.02.42 PM.png

We now call our decorator here because we're not executing the decorator function, but we're executing a function that will return such a decorator function. And the advantage just is that we now can pass a values which will be used by that inner returned decorator function.