Decorators in Typescript

Rodrigo Luque
2 min readJan 17, 2023

Decorators are a powerful feature of TypeScript that allow you to add functionality to your classes and properties without modifying their implementation. They are essentially functions that are executed when the decorator is applied to a class or property, and can be used for a wide range of tasks such as logging, validation, or caching.

To create a decorator, you first need to define a function that will be executed when the decorator is applied. Here is an example of a simple decorator that logs the value of a property whenever it is accessed or modified:

Example of “log” decorator

The decorator in this example, is the log method, which takes 2 arguments (target & key) which represent the object and property that the decorator is applied to, respectively.
The decorator is then applied to a property by prefixing the property with the @ symbol followed by the name of the decorator function. In this case, the decorator is applied to the myProp property of the MyClass class.

This is a simple example, but decorators can be used to accomplish much more complex tasks, such as adding validation or caching to your code. They can also be applied to methods and classes, not only to properties, allowing you to add functionality to the class as a whole.

Decorators also can be composed, allowing you to apply multiple decorators to a single class or property. This can be useful when you want to add multiple functionalities to a class or property.

Example of “log” and “measure” decorators

The order in which the decorators are applied is important, and it follows the order of the decorators in the class definition. Therefore, in this example, the decorator log would be applied before the decorator measure.

As you can see, decorators can be very helpful whenever you want to add a wrapper function over a class or a prop, and the use cases are endless.

And you, what do you use decorators for?

--

--

Rodrigo Luque

Software Developer based in Madrid, Spain 👨🏻‍💻. I consider myself a curious person in constant desire of improvement.