I use a Proxy
object with the idea that whenever a property gets updated, some other side-effect can also be initiated. I don't want to initiate the side effects in the many places that properties get set (DRY principle).
Somewhat contrived example code:
const session = new Proxy(
{ id: undefined as number, age: undefined as number}, // =target
{
set: (target, property, value): boolean => {
switch (property) {
case 'id': {
target[property] = value;
this.notifyIdWasUpdated(value);
return true;
}
case 'age': {
target[property] = value;
this.updateAgeDisplay(value);
return true;
}
default: {
return false;
}
}
}
}
);
My problem is that when I use my IDE's refactoring to change a property name (key) of the target
object (e.g. age
), the string constants in the case
statements (e.g. 'age'
) don't get updated as well (potentially causing a bug).
Question: Is there a way to dynamically get a string value 'key'
from an expression obj.key
in the case
statement (which would then be refactoring proof)? (Sort of the inverse of the ['key']
accessor, in a way...) Alternatively, can you suggest another way to structure the above code to guard against this sort of programmer oversight?
- I have found Get object property name as a string, but wonder if there is a less "iffy" solution - IMHO the tradeoff between a potential problem and adding a lot of code to guard against it is not worth it. (Many techniques seem to iterate through all keys and match on either property type or value; these will not be safe enough.)
- Typescript's documentation seems to say that metadata emission for reflection-like use is not yet officially adopted. Also not worth it IMHO to add a whole experimental library just for this.