I was recently exploring Typescript property decorators, and I encountered some unexpected behavior in the following code:
function dec(hasRole: boolean) {
return function (target: any, propertyName: string) {
let val = target[propertyName];
Object.defineProperty(target, propertyName, {
get() { return val; },
set(value) { val = hasRole; }
});
}
}
class Hey {
age: number;
@dec(true)
hasRole: boolean = false;
constructor(age: number) {
this.age = age;
}
}
let ob = new Hey(22);
console.log(ob);
//Output:
age: 22
hasRole: true
__proto__:
constructor: class Hey
hasRole: true
get hasRole: ƒ get()
set hasRole: ƒ set(value)
__proto__: Object
I expected the output to be: 1. OwnProperty -> hasRole = false 2. Prototype property -> hasRole = true. The argument 'target' in the decorator provides the constructor function for static members or prototype of the class for instance members, which may explain the observed functionality.
Would appreciate an explanation on this behavior.