- Typescript Daily
- Posts
- Wake Up, Devs! You've Been Logging All Wrong!
Wake Up, Devs! You've Been Logging All Wrong!
Harness TypeScript's Method Decorators for Flawless Execution!
🎯 TypeScript Daily Digest!
Advanced Feature: Method Decorators in TypeScript
Problem Statement: As applications grow, we often find a need to execute repetitive tasks or logic around method calls, like logging, performance monitoring, or access control. Writing this repeatedly is not only redundant but also error-prone. Method decorators in TypeScript offer a solution to this by letting us wrap additional logic around the method invocations.
Use Case: Imagine you're working on an e-commerce application. Every time a user action is executed, such as adding an item to the cart, you want to log the method's invocation for analytics or debugging purposes. Rather than manually inserting console.log
everywhere, you could use a method decorator to automate this.
Snippet:
Explanation:
Function
logInvocation
:This function returns another function. This inner function is a decorator function.
The decorator function logs a message indicating which method was invoked.
Class
ShoppingCart
:It contains a method called
addItem
.We have decorated this
addItem
method with@logInvocation()
. This means wheneveraddItem
is called, our decorator function fromlogInvocation
will also get executed.
Usage:
We create a new instance of the
ShoppingCart
class.Then we call the
addItem
method of this instance with 'Book' as an argument.Due to the decorator, two things happen in sequence:
Our decorator logs "
addItem Invoked
".The
addItem
method then logs "Book added to the cart!
".
In essence, the code uses a TypeScript decorator to add an extra behavior (logging in this case) to the addItem
method of the ShoppingCart
class without changing its original code.
Note:
For TypeScript versions below 5.0, the above style is effective. (Reference - https://www.typescriptlang.org/docs/handbook/decorators.html#decorators)
However, starting from TypeScript version 5.0 and later, there's support for the ClassMethodDecoratorContext
type, allowing for a more refined approach to method decorators. (Reference - https://devblogs.microsoft.com/typescript/announcing-typescript-5-0/#decorators)
Real-World use-cases:
Reply