Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 633
user2520818 Avatar asked Apr 27 '26 14:04

user2520818


1 Answers

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
like image 55
Max Koretskyi Avatar answered Apr 30 '26 05:04

Max Koretskyi