Is there a way to transfer the functionalities of a class into another object? Let's consider this example:
class FooBar {
private service: MyService;
constructor(svc: MyService) {
this.service = svc;
}
public foo(): string {
return "foo";
}
public bar(): string {
return "bar"
}
public fooBar(): string {
return "foobar"
}
}
let obj = new FooBar();
export default {
...obj
};
I am looking to have all the methods of the class FooBar
in the exported object without including the private property service
. However, since these methods are added to the prototype object in JavaScript compilation, they are not part of the spread operation and the private property ends up included in the resulting object.
One solution that works is:
export default {
foo: obj.foo.bind(obj),
bar: obj.bar.bind(obj),
fooBar: obj.fooBar.bind(obj),
};
If possible, I would like to avoid this approach as I will need to map methods from multiple classes.
Important Note: This is specifically for combining GraphQL resolvers into a single object to be used with the graphql
function.
I am currently running my application using ts-node
, in case that matters.