Questions
What are decorators and how do you use them in TypeScript?
The Scenario
You are a frontend engineer at a fintech company. You are building a new framework that will be used to build REST APIs.
You want to be able to add metadata to your code, such as the HTTP method and the URL path, so that you can automatically generate the API documentation.
The Challenge
Explain what decorators are in TypeScript and how you would use them to solve this problem. What are the key benefits of using decorators?
A junior engineer might not be aware of decorators. They might try to solve this problem by using comments or a separate configuration file, which would be a less elegant and less robust solution.
A senior engineer would know that decorators are the perfect tool for this job. They would be able to explain what decorators are and how to use them to add metadata to code. They would also have a clear plan for how to use decorators to automatically generate the API documentation.
Step 1: Understand What Decorators Are
A decorator is a special kind of declaration that can be attached to a class declaration, method, accessor, property, or parameter. Decorators use the form @expression, where expression must evaluate to a function that will be called at runtime with information about the decorated declaration.
Step 2: Write a Simple Decorator
Here’s how we can write a simple decorator to specify the HTTP method and the URL path of a REST API endpoint:
function RequestMapping(value: string, method: string) {
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
// ... (store the metadata) ...
};
}Step 3: Use the Decorator
We can use the decorator on a method in our controller class:
class MyController {
@RequestMapping("/hello", "GET")
hello() {
return "Hello, world!";
}
}Step 4: Process the Decorator
We can use reflection to process the decorator at runtime and automatically generate the API documentation.
The Benefits of Using Decorators
| Benefit | Description |
|---|---|
| Metadata | Decorators provide a way to add metadata to code, which can be used by tools and frameworks. |
| Readability | Decorators can make your code more readable by making it clear what the code is intended to do. |
| Extensibility | You can create your own custom decorators to add new functionality to your code. |
Practice Question
You want to create a new decorator that can be used on both methods and properties. Which of the following would you use?