Skip to content

Instantly share code, notes, and snippets.

@mmichlin66
Last active October 15, 2020 01:59
Show Gist options
  • Save mmichlin66/46257804ef630a2850dda2fa9193b2e4 to your computer and use it in GitHub Desktop.
Save mmichlin66/46257804ef630a2850dda2fa9193b2e4 to your computer and use it in GitHub Desktop.
Virtualizing TypeScript Properties with Proxy and Decorator - listing 4
export function virtual( target: any, name: string)
{
// symbol to keep the proxy handler value
let sym = Symbol( name + "_proxy_handler");
Object.defineProperty( target, name, {
enumerable: true,
get()
{
// get the proxy from the handler
return this[sym]?.proxy;
},
set(v)
{
// check whether we already have the handler and created it if we don't
let handler = this[sym];
if (!handler)
this[sym] = handler = new VirtHandler();
// create a new proxy each time because we want the proxy to have the new value.
handler.proxy = new Proxy( v, handler);
// set the new vaule to the handler so that it will use it from now on
handler.target = v;
}
});
}
class VirtHandler
{
target: any;
get( t: any, p: PropertyKey, r: any): any
{
return this.target[p];
}
}
class Base
{
@virtual first = { v: 1 };
second = this.first;
}
class Derived extends Base
{
first = { v: 2 };
}
let obj = new Derived();
console.log( obj.second.v);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment