Search⌘ K
AI Features

Types of Decorators

Explore the four main types of TypeScript decorators: class, property, method, and parameter decorators. Understand how each decorator function is invoked with specific parameters at runtime. Discover how to create decorator factory functions to pass parameters to decorators, enhancing customization and flexibility in your TypeScript classes and methods.

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:

Files
index.ts
tsconfig.json
TypeScript 4.9.5
// 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 ...