In an effort to learn how Proxy works I wanted to try and make a Proxied class that can handle any property name, even those that don't exist in the class, while still maintaining access to old properties. I assumed Typescript would let you do this natively (since this is one of Proxy use cases after all) when a class is Proxied but I sadly discovered this is not the case. When i try to do something like this:
const handler = {
get: (target: any, key: string) => {
return key;
},
set: (target: any, key: string, value: any) => {
console.log(target, key, value);
return true;
}
};
class ProxTest {
private storage: {[key: string]: any} = {};
public a: number;
constructor() {
return new Proxy(this, handler);
}
}
const c = new ProxTest();
c.val = "b"; //Gives error
I get an error trying to access c.val
. I have found a "solution", that's to use "Index Signatures" and add //@ts-ignore to all the other properties.
const handler = {
get: (target: any, key: string) => {
return key;
},
set: (target: any, key: string, value: any) => {
console.log(target, key, value);
return true;
}
};
class ProxTest {
//@ts-ignore
private storage: {[key: string]: any} = {};
//@ts-ignore
public a: number;
[key: string]: any;
constructor() {
return new Proxy(this, handler);
}
}
const c = new ProxTest();
c.val = "b";
This is the only solution I found so far and to be honest I don't really like it. Is there some other way to do this?
To be clear, this code is just an example of the general issue (not being able to use arbitrarily named properties on a proxied object) and it's in no way shape or form related to some code i'm actually using. But since this seems something one should be able to do when using Proxy in typescript i'd like to find a general solution