Close

TypeScript - Accessor Decorators

[Updated: Mar 19, 2019, Created: Mar 17, 2019]

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.ts

function 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.ts

function 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 Project

Dependencies and Technologies Used:

  • Typescript 3.3.3333
TypeScript - Accessor Decorators Select All Download
  • typescript-accessor-decorator-examples
    • Ex1AccessorDecorator.ts

    See Also