mbehzad
mbehzad

Reputation: 3878

Using ES decorators on class get and set methods

is it ok according to the decorator proposal to have a decorator on a class getter or setter? Or are they only allowed on normal methods? e.g.

class Foo extends Bar {

  @override
  get someProp() {
    super.someProp + 2;
  }
}

some libraries / frameworks provide such decorators. But for example the babel parser babylon marks that as an error!

Upvotes: 3

Views: 464

Answers (1)

Max Koretskyi
Max Koretskyi

Reputation: 105497

I think it's perfectly fine from the perspective of the decorator to be applied to a setter/getter field, basically any field. Since "normal" property and setter/getter property differ in the type of property descriptor - data descriptor vs accessor descriptor and the decorator is applied to a property descriptor it can be applied to any property, including "setter/getter" and "method" properties.

For example, you can change the setter to "normal" property inside the decorator:

function removesetter(klass, prop, descriptor) {
    return {
        value: 5,
        writable: true
    }
}

class Foo {
    @removesetter
    get someProp() {
        return 3;
    }
}

const f = new Foo();
console.log(f.someProp); // 5

Upvotes: 2

Related Questions