Search⌘ K
AI Features

Class and Property Decorators

Explore the use of TypeScript class and property decorators to modify class definitions and properties at runtime. Understand how decorators work with normal and static properties and how to access and manipulate class constructors and prototypes.

Class decorators

We know that in order to define a class decorator, we must define a function that has a single parameter, which is of type Function.

Let’s take a closer look at this parameter:

TypeScript 4.9.5
// Define a function called classConstructorDec which takes a constructor function as input and logs it to the console
function classConstructorDec(constructor: Function) {
console.log(`constructor : ${constructor}`);
}
// Apply the classConstructorDec decorator to the ClassWithConstructor class
@classConstructorDec
class ClassWithConstructor {
constructor(id: number) { }
}
Decorator function to log constructor information
  • We have a decorator function named classConstructorDec, which logs the value of the constructor argument to the console.

  • We then apply this decorator to a class named ClassWithConstructor on line 7.

  • This ClassWithConstructor class has a single constructor function that accepts a single parameter named id of type number.

We can see from the output that the decorator was invoked with a single argument, which is the definition of the constructor function itself. Note that this definition is the JavaScript definition and not the TypeScript definition, as there is no type for the id parameter.

What this is showing us is that a class decorator will be called with the definition of the class constructor itself. Note that the exact output of this code depends on the target version that we have specified, which is "es5". If we change this to "es6", we will generate a ...