...

/

Types of Decorators

Types of Decorators

Learn about the different types of decorators in JavaScript and their use cases.

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:

index.ts
tsconfig.json
// Define a function called classDecorator which takes a constructor function as input
function classDecorator(
constructor: Function
) {}
// Define a function called propertyDecorator which takes an object and a string property key as input
function 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 input
function 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 input
function parameterDecorator(
target: any,
methodName: string,
parameterIndex: number
) {}
Decorators for class members

Here, we have four functions, each with slightly different parameters:

  • Lines 2–4: The first function, named classDecorator, has a ...