Skip to content

Instantly share code, notes, and snippets.

@takeru
Created October 18, 2023 03:23
Show Gist options
  • Save takeru/86f1dbce2025d281095d02d62a6626e7 to your computer and use it in GitHub Desktop.
Save takeru/86f1dbce2025d281095d02d62a6626e7 to your computer and use it in GitHub Desktop.
typescriptでメタプログラミング ProxyとReflect
function proxy(obj: any) {
return new Proxy(obj, {
set: function (target, property, value, receiver) {
console.log(`[proxy.set] property=${String(property)} value=${value}`);
return Reflect.set(target, property, value, receiver);
},
get: function (target, property, receiver) {
const value = Reflect.get(target, property, receiver);
if (typeof value !== "function") {
console.log(`[proxy.get] property=${String(property)}`);
return value;
} else {
const func = value as Function;
const func_proxy = new Proxy(func, {
apply: function (target, thisArg, argumentsList) {
console.log(
`[proxy.apply] target=${String(
property
)} argumentsList=${argumentsList}`
);
return Reflect.apply(target, thisArg, argumentsList);
},
});
return func_proxy;
}
},
});
}
class Foo {
bar;
constructor(n: number) {
this.bar = n;
}
baz(n: number) {
console.log(`bar ${n}`);
}
}
const x = (foo: Foo) => {
console.log(foo.bar);
foo.bar = 2;
foo.baz(3);
}
x(new Foo(1));
x(proxy(new Foo(10)));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment