I'm currently working on a project that involves creating a decorator to override a property and define a hidden property. Let's take a look at the following example:
function customDecorator() {
return (target: any, key: string) => {
let hiddenKey = '_' + key;
// Define a hidden property
Object.defineProperty(target, hiddenKey, {
value: 0,
enumerable: false,
configurable: true,
writable: true
});
// Override property get/set
return Object.defineProperty(target, key, {
enumerable: true,
configurable: true,
get: () => target[hiddenKey],
set: (val) => {
target[hiddenKey] = target[hiddenKey] + 1;
}
});
};
}
class ExampleClass {
@customDecorator()
propA = null;
propB = null;
}
let instance = new ExampleClass();
console.log(Object.keys(instance), instance.propA, instance._propA, instance);
The current output is:
[ 'propB' ] 1 1 A { propB: null }
However, the expected output is:
[ 'propA', 'propB' ] 1 1 A { propA: 1, propB: null }
despite propA
being enumerable.
If we replace the get
and set
with:
get: function () {
return this[hiddenKey]
},
set: function (val) {
this[hiddenKey] = this[hiddenKey] + 1;
}
We now get:
[ '_propA', 'propB' ] 1 1 A { _propA: 1, propB: null }
even though _propA
has its enumerable
set to false
.
It seems like there are some unexpected behaviors happening here. I would appreciate an explanation of what is going on and how to achieve the desired outcome in this scenario.