Regarding the following example code, is there any type-safe way of automatically forwarding any of the prototypal method calls, each to its related method of another object?
class Foo {
greet() {
return "hello";
}
sayGoodbye() {
return "bye";
}
// ... many more methods
}
class Bar {
foo: Foo;
constructor() {
this.foo = new Foo();
}
greet() {
this.foo.greet();
}
sayGoodbye() {
this.foo.sayGoodbye();
}
// ...
}
We don't have to write method() { foo.method() }
for all methods on Foo
? I.e. something like how in JavaScript we could do Object.getOwnPropertyNames(Foo.prototype).forEach(...)
and point the methods to foo
, but in a type-safe way?
I've tried mixins but I find those hard to work with since those invert the relationship (Foo
has to subclass Bar
, so I can't e.g. instantiate Foo
with specific parameters when declaring Bar
).
Object.getOwnPropertyNames(Foo.prototype).forEach(...)
is a totally type-safe approach for implementing forwarding, based on an aggregated property, in a generic way. Or do you mean, you are looking for a TypeScript yoga/gymnastics-figure which is capable of expressing such a pattern?