Start Implementing your own Typescript Class Decorators

Start Implementing Your Own Typescript Class DecoratorsClass DecoratorWhat is a Decorator?It is a structural design pattern that lets you attach new behaviors to objects by placing these objects inside special wrapper objects that contain the behaviors…


This content originally appeared on Level Up Coding - Medium and was authored by Poorshad Shaddel

Start Implementing Your Own Typescript Class Decorators

Class Decorator

What is a Decorator?

It is a structural design pattern that lets you attach new behaviors to objects by placing these objects inside special wrapper objects that contain the behaviors (reference).

Typescript Class Decorators Definition: The class decorator is applied to the constructor of the class and can be used to observe, modify, or replace a class definition.(reference)

What is going on behind the scene?

Your class decorator is actually a simple function that is called as a function at runtime and it gets one argument and that is the constructor function of the class. If the class decorator returns something it is going to be used as the constructor of the class. These things might sound confusing but it’s going to be clear as day after taking a look at some pieces of code.

Setup

In order to run the Typescript code, we need to compile them using the Typescript compiler.

We need a tsconfig.json file :

We have to enable the experimentalDecorators. Also, the target should not be less than ES5.

If you do not want to use a tsconfig file you can pass these options directly:

tsc --experimentalDecorators // If you installed tsc globaly
npx tsc --experimentalDecorators // If you installed tsc in your current directory

Now by running tsc in the current directory, the typescript files will compile to Javascript files and we can run them using Node.(reference)

Define a Class Decorator

First class decorator we want to create is just going to log a message on the console and tell us that it is running.

Now if I compile and run this code I will see this on the console:

Result of running the code

Here the class decorator was a function that had constructor of the class as its argument and logs something on console easy-peasy. We can see that before running the constructor of the class it runs the class decorator.

Let’s see an example that we can pass our constructor in the decorator:

In order to make some changes to constructor of the class from the class decorator we have to return a class that extends the base class.

The Typescript compiler forces us to do this(return a class that extends the base class).

Why compiler is forcing us do this? Because otherwise the type we are returning is not compatible with the base class.

If what is happening is still vague you should recall that classes are actually functions(You may find so many helpful comments on that here).

Now that we know this, consider the class decorator as a higher order function. It is somehow similar to the implementation of method decorator.

What if we want to use a class decorator on all classes? That is possible by using Typescript Generics. Take a look at this example:

We can use this class decorator on all classes.

<T extends { new (...args: any[]): {} }>

This is the definition of generic and if you are wondering why it extends { new (...args: any[]): {} you should know that we expect a constructor function and this is how we can tell the compiler to check that.

Here T is the generic class and we are able to return new constructor by extending it in line 4.

In line 5 and 6 we added two timestamps members to the class. Now each class that wrapped by this decorator has these two timestamps created_at and updated_at .

Let’s see the result on console:

Timestamp Decorator

As we can see class has two additional members updated_at and created_at

Can we access these two additional properties?

Calling Additional Properties that added by Decorator
The Decorator does not change the Typescript Type

The only way to access that property is to tell the compiler to ignore that line. If you consider timestamps example, we usually want to pass them to an ORM or ODM to save a record or document in the database, so there should be no problem even if we do not call them directly. These properties are going to be passed in the object.

Another really useful decorator that is mentioned in official TS Docs is sealed decorator.

Sealed Decorator

When we seal a class we want to prevent more functionalities and properties to be added or removed. Let’s see that in action:

We sealed the constructor and it’s prototype. If we try to change the constructor this way(We had to ignore the compiler to be able to do this):

That will result in a TypeError:

Result of changing a class prototype

If we do not use @sealed decorator then this is going to be the result:

Calling getHeight without sealed decorator

Conclusion

Class decorators are simply a function that runs at runtime and it can change behavior of a class. Using Class Decorators and wrapping other classes can be a little bit tricky in some cases if you want to add some functionalities to them since the decorator does not change the typescript type.

Decorators are widely used in Angular and NestJS since both of these frameworks use OOP paradigm and you can take a look at their documents and the implementation of decorators.


Start Implementing your own Typescript Class Decorators was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Level Up Coding - Medium and was authored by Poorshad Shaddel


Print Share Comment Cite Upload Translate Updates
APA

Poorshad Shaddel | Sciencx (2021-12-23T12:53:42+00:00) Start Implementing your own Typescript Class Decorators. Retrieved from https://www.scien.cx/2021/12/23/start-implementing-your-own-typescript-class-decorators/

MLA
" » Start Implementing your own Typescript Class Decorators." Poorshad Shaddel | Sciencx - Thursday December 23, 2021, https://www.scien.cx/2021/12/23/start-implementing-your-own-typescript-class-decorators/
HARVARD
Poorshad Shaddel | Sciencx Thursday December 23, 2021 » Start Implementing your own Typescript Class Decorators., viewed ,<https://www.scien.cx/2021/12/23/start-implementing-your-own-typescript-class-decorators/>
VANCOUVER
Poorshad Shaddel | Sciencx - » Start Implementing your own Typescript Class Decorators. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/12/23/start-implementing-your-own-typescript-class-decorators/
CHICAGO
" » Start Implementing your own Typescript Class Decorators." Poorshad Shaddel | Sciencx - Accessed . https://www.scien.cx/2021/12/23/start-implementing-your-own-typescript-class-decorators/
IEEE
" » Start Implementing your own Typescript Class Decorators." Poorshad Shaddel | Sciencx [Online]. Available: https://www.scien.cx/2021/12/23/start-implementing-your-own-typescript-class-decorators/. [Accessed: ]
rf:citation
» Start Implementing your own Typescript Class Decorators | Poorshad Shaddel | Sciencx | https://www.scien.cx/2021/12/23/start-implementing-your-own-typescript-class-decorators/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.