- Mastering TypeScript 3
- Nathan Rozentals
- 326字
- 2021-07-02 12:42:57
Property decorators
Property decorators are decorator functions that can be used on class properties. A property decorator is called with two parameters—the class prototype itself, and the property name. As an example of this, consider the following code:
function propertyDec(target: any, propertyKey : string) { console.log(`target : ${target}`); console.log(`target.constructor : ${target.constructor}`); console.log(`class name : ` + `${target.constructor.name}`); console.log(`propertyKey : ${propertyKey}`); } class ClassWithPropertyDec { @propertyDec name: string; }
Here, we have defined a property decorator named propertyDec that accepts two parameters—target and propertyKey. The target parameter is of type any, and the propertyKey parameter is of type string. Within this decorator, we are logging some values to the console. The first value we log to the console is the target argument itself. The second value logged to the console is the constructor property of the target object. The third value logged to the console is the name of the constructor function, and the fourth value is the propertyKey argument itself.
We are then defining a class named ClassWithPropertyDec that is now using this property decorator on the property named name. As in the case of class decorators, the syntax used to decorate a property is simply @propertyDec before the property to be decorated.
The output of this code is as follows:
target : [object Object] target.constructor : function ClassWithPropertyDec() { } target.constructor.name : ClassWithPropertyDec propertyKey : name
Here, we can see the output of our various console.log calls. The target argument resolves to [object Object], which simply indicates that it is an object prototype. The constructor property of the target argument resolves to a function named ClassWithPropertyDec, which is, in fact, our class constructor. The name property of this constructor function gives us the name of the class itself, and the propertyKey argument is the name of the property itself.
Property decorators, therefore, give us the ability to check whether a particular property has been declared on a class instance.