I find myself in a situation where I am interested in utilizing the Proxy
feature to implement "load balancing" among a collection of classes.
To illustrate my approach, consider the following simple example:
class Foo {
constructor(private msg: string) {}
foo() {
console.log(this.msg);
}
}
// @ts-ignore
const proxy: Foo = new Proxy([new Foo('foo'), new Foo('bar')], {
get: (o, key) => {
const client = o[Math.floor(Math.random() * o.length)];
console.log(client, key);
return client[key];
},
});
proxy.foo();
This implementation seems to be functional. However, things become complicated when dealing with TypeScript. The type definition of Proxy
hinders us from carrying out something like:
new Proxy<Foo>([new Foo(), new Foo()], handler)
This particular code snippet leads to an error message stating:
Argument of type 'Foo[]' is not assignable to parameter of type 'Foo'.
Is there any way to accomplish this task without sacrificing type safety?