I'm currently trying to update a field decorator from experimental TypeScript to stage 3. All it does is send a notification when the value of a field is updated. The old implementation looks like this:
function watchChange<T extends Object>(target: T, key: keyof T & string) {
console.log('Calling the watch change decorator')
let property = target[key];
const getter = ()=>{
return property
};
const setter = (newVal: any) =>{
console.log(`${key} changed from ${property} to ${newVal}`)
property = newVal
}
Object.defineProperty(target, key, {
get: getter,
set: setter,
configurable: true,
enumerable: true
})
}
My current attempt to do the same with stage 3 decorators looks like this:
function watchChange<T, V>(target: any, context: ClassFieldDecoratorContext<T, V>) {
return function(value: V) {
const setter = (newVal: any) =>{
console.log(`${context.name as string} changed from ${value} to ${newVal}`)
this[context.name] = newVal
}
context.access.set = setter
return value
}
}
context.access.set requires one additional obj parameter. What is it? Currently the documentation is very scarce. This doesn't work. Why and how can it be implemented?
You need to use Object.defineProperty
in the return init-func
, instead of modifying the context.