Create an custom Decorator in Typscript
Would you like to create your own decorator, but don’t know how to do it?
Decorators are essential for typescript developers, they allow you to standardize the behavior of a function by adding other features to it. decorators are pieces of code that can be reused in any typscript context, they are very used in the Angular world and also Vue.js .. for example @Component by Angular, is a decorator created to wrap the class, providing it with other features.
A decorator can receive external parameters for its correct functioning, force the function to return a certain value, alter its operation at runtime or perhaps check that the logged in user can perform a certain function.
There are different types of decorators, class, attribute and method decorator, there are also decorators for parameters passed to functions
In this example we see how a function decorator is created.
We will create a log decorator,well let’s proceed to the creation the @Log decorator.
This will receive in input the type of level log: “log” | “debug” | “information” | “warn” and shows to console a log with the name of the class, the value of the parameters in input , method name and the value of the parameters in otuput, again, the log shows the time to execute this function
Above we created @Log decorator, ok, but how to use it?
This is ready to use, just put @Log upper an function and it’s ok.
Now in console,open tab debug and we will see this result
if you have specifid type info and not debug, open console in info tab for see log!
Olso for warning!
Thanks for watching.