Class and Property Decorators
Learn about class decorators, their parameters, and modifying class definitions, including property decorators and static class properties.
We'll cover the following...
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:
// Define a function called classConstructorDec which takes a constructor function as input and logs it to the consolefunction classConstructorDec(constructor: Function) {console.log(`constructor : ${constructor}`);}// Apply the classConstructorDec decorator to the ClassWithConstructor class@classConstructorDecclass ClassWithConstructor {constructor(id: number) { }}
-
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 namedid
of typenumber
.
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 ...