I am trying to learn Decorators in Typeand was following one of Fireship's Lessons.
Stackblitz - https://stackblitz.com/edit/typescript-7osiaa?file=index.ts
I created the below class IceCreamComponent
when modifying flavor variable the setter for the Object redefined using Object.defineProperty
is not being called and instead the changed value is being updated which is visible when logging the variable to the console.
Any help is appreciated, Thanks.
class IceCreamComponent {
@Emoji()
flavor = 'vanilla';
constructor() {
this.flavor = 'Orange';
}
changeFlavor(val) {
this.flavor = val;
}
logFlavor() {
console.log(this.flavor);
}
}
function Emoji() {
console.log('Emoji decorator wrapper called');
return function (target: Object, key: string | symbol) {
console.log(target[key]); // Undefined
console.log('Decorator called', key); // Flavor
let val = target[key];
const getter = () => {
console.log('Getter');
return val;
};
// Why is the setter not triggered
const setter = (next) => {
console.log(`Updating Flavor ....`);
val = ` ${next} `;
};
Object.defineProperty(target, key, {
get: getter,
set: setter,
enumerable: true,
configurable: true,
});
};
}
let iceCream = new IceCreamComponent();
iceCream.logFlavor(); // Orange
iceCream.changeFlavor('Red');
iceCream.logFlavor(); // Red