Method and Parameter Decorators
Learn how to use method and parameter decorators in TypeScript to modify the behavior of methods and their parameters within a class.
We'll cover the following...
Method decorators
Recall that method decorators can be applied to methods within a class and that they have three parameters.
Let’s take a look at a method decorator as follows:
// Define a methodDec function which logs the target, method name, descriptor, and target methodfunction methodDec(target: any,methodName: string,descriptor?: PropertyDescriptor) {console.log(`target: ${target}`);console.log(`methodName : ${methodName}`);console.log(`descriptor : ${JSON.stringify(descriptor)}`);console.log(`target[methodName] : ${target[methodName]}`);}
Here, we have a method decorator named methodDec
, which has three parameters,
namely target
of type any
, methodName
of type string
, and an optional parameter named descriptor
of type PropertyDescriptor
. Within this decorator, we log the values of the target
, methodName
, and descriptor
parameters to the console. Finally, we log the value of the methodName
property of the target
object to the console, using the syntax target[methodName]
.
Let’s apply this decorator to a class as follows:
// Define a ClassWithMethodDec class and apply the methodDec decorator to its print methodclass ClassWithMethodDec {@methodDecprint(output: string) {console.log(`ClassWithMethodDec.print(${output}) called.`);}}
Here, we have a class named ClassWithMethodDec
, which has a single method named print
, which has a single parameter named output
of type string
. This print
method has been decorated with our methodDec
decorator.
We can see the values of each of the arguments that were passed into the decorator from the JavaScript runtime in the output.
-
The
target
argument indicates that this is an object, as it would be for a class definition. -
The
methodName
argument is the ...