Property decorators are prefixed to property declarations. The signature of PropertyDecorator in the TypeScript source code is this:
declare type PropertyDecorator = (target: Object, propertyKey: string | symbol) => void;
The following is a code snippet of a class with a property decorator applied to a property. In this code, the firstname property is decorated with the @hashify property decorator:
class Customer {
@hashify
public firstname: string;
public lastname: string;
constructor(firstname : string, lastname : string) {
this.firstname = firstname;
this.lastname = lastname;
}
}
Now, we will see the code snippet of the @hashify property decorator function:
function hashify(target: any, key: string)
{
var _value = this[key];
var getter = function ()
{
return '#' + _value;
};
var setter = function (newValue)
{
_value = newValue;
};
if (delete this[key])
{
Object.defineProperty(target, key,
{
get: getter,
set: setter,
enumerable: true,
configurable: true
});
}
}
The _value variable holds the value of the property that is being decorated. Both the getter and setter functions will have access to the _value variable, and here, we can manipulate the _value variable by adding extra behaviors. I have concatenated # in getter to return hash tagged first name. Then, we delete the original property from the class prototype using the delete operator. A new property will be created with the original property name and the extra behavior.