1. Introduction
# Typescript Decorator
Medium
Decorators are a special type of declaration that can be attached to class declarations, methods, accessors, properties, or parameters. Decorators use the form, where must evaluate to a function. It is called at runtime, with the decorated declaration information passed as a parameter. Decorators are generally used to handle logic unrelated to the class or its properties. For example, measuring the execution time of a class method or logging can be written as a separate decorator. In Node.js, a framework that uses decorators well is NestJS. However, if you are not familiar with it, it's okay. I will explain the use of decorators according to my understanding. To enable the decorator feature, please enable the compiler option in .
Document in this article is based on decorators, but examples are written in a way which could be used in nestjs.
Quick Start
Sometimes, we may need to perform type checking on incoming parameters, sort and filter return values, add throttling and debouncing to functions, or other functional code based on multiple class inheritances. There are various repetitive codes that are unrelated to the logic of the function itself. For example, we want to record the login time when a user logs in.
The above code forcibly writes the code for logging into the login logic processing, so the higher the code volume, the more redundant the code. We need to separate the logging logic and make the login method more focused on handling the login logic. Next, we will simulate the principle of decorators using higher-order functions to better understand decorators later.
Decorator types
There are several types of decorators in <b>Typescript</b>:
- Class decorators
- Property decorators
- Method decorators
- Parameter decorators
- Accessor decorators
Each of these decorators can work on the class prototype (prototype attribute) and the class itself, respectively
After understanding the above concepts, let's move on to learning about the real decorators.