The accessor decorators are same as method decorators but they are applied to either setter or getter method.
TypeScript disallows decorating both the get and set accessor for a single member. Instead, all decorators for the member must be applied to the first accessor specified in document order.
Examples
Ex1AccessorDecorator.tsfunction Enumerable(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
//make the method enumerable
descriptor.enumerable = true;
}
class Person {
_name: string;
constructor(name: string) {
this._name = name;
}
@Enumerable
get name() {
return this._name;
}
}
console.log("-- creating instance --");
let person = new Person("Diana");
console.log("-- looping --");
for (let key in person) {
console.log(key + " = " + person[key]);
} Output-- creating instance -- -- looping -- _name = Diana name = Diana
Using a decorator on both getter and setter will end up in compile time error:
Ex2AccessorDecorator.tsfunction Enumerable2(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
//make the method enumerable
descriptor.enumerable = true;
}
class Person2 {
_name: string;
constructor(name: string) {
this._name = name;
}
@Enumerable
get name() {
return this._name;
}
@Enumerable
set name(n: string) {
this._name=n;
}
}
Ex2AccessorDecorator.ts:18:5 - error TS1207: Decorators cannot be applied to multiple get/set accessors of the same name.
18 @Enumerable
Example ProjectDependencies and Technologies Used: |