If you find yourself in need of the specific functionality you are describing, one option is to utilize a true Proxy
, provided that your JavaScript engine supports ECMAScript 2015 or newer. While this approach may be considered excessive for your particular situation, if MyNamesStrings
remains unchanged, converting it to MyNames
just once would be more efficient. However, for the sake of discussion, let's assume the use of a proxy is necessary. Below is one potential implementation:
function makeStringWrappingProxy<T extends object>(t: T): T {
return new Proxy(t, {
get<K extends keyof T>(target: T, prop: K) {
const val = target[prop];
if (typeof val === 'string') {
return '[${' + val + '}]';
} else if (typeof val === 'object') {
return makeStringWrappingProxy(val as T[K] & object);
} else {
return val;
}
}
});
}
The concept involves creating a proxy that intercepts all attempts to access properties within the object. When retrieving a string property, it will return the wrapped string instead. In the case of an object property, it will return a proxy for that property (allowing for nested property wrapping). Otherwise, it simply returns the property itself.
Let's observe this in action:
const MyNames = makeStringWrappingProxy(MyNamesStrings);
const ab = MyNames.a.b //"[${hello}]" expected output
const ac = MyNames.a.c //"[${bye}]" also expected result.
As demonstrated, the solution works as intended! It is important to note that utilizing proxies comes with trade-offs - they may not offer optimal performance (each property access triggers function calls), compatibility issues with older versions of ECMAScript, and can lead to unexpected behaviors (modifying a property may not reflect the change when accessed later). The decision ultimately lies with your specific requirements.
I hope this explanation proves helpful. Best of luck!