Types of Decorators
Learn about the different types of decorators in JavaScript and their use cases.
We'll cover the following...
Introduction to decorator types
Decorators are functions that are invoked by the JavaScript runtime when a class is defined. Depending on what type of decorator is used, these decorator functions will be invoked with different arguments.
Let’s take a quick look at the types of decorators, which are:
-
Class decorators: These are decorators that can be applied to a class definition.
-
Property decorators: These are decorators that can be applied to a property within a class.
-
Method decorators: These are decorators that can be applied to a method on a class.
-
Parameter decorators: These are decorators that can be applied to a parameter of a method within a class.
As an example of these types of decorators, consider the following code:
// Define a function called classDecorator which takes a constructor function as inputfunction classDecorator(constructor: Function) {}// Define a function called propertyDecorator which takes an object and a string property key as inputfunction propertyDecorator(target: any,propertyKey: string) {}// Define a function called methodDecorator which takes an object, a string method name, and an optional property descriptor object as inputfunction methodDecorator(target: any,methodName: string,descriptor?: PropertyDescriptor) {}// Define a function called parameterDecorator which takes an object, a string method name, and a number representing a parameter index as inputfunction parameterDecorator(target: any,methodName: string,parameterIndex: number) {}
Here, we have four functions, each with slightly different parameters:
-
Lines 2–4: The first function, named
classDecorator
, has a ...