I am seeking a way to dynamically incorporate methods that are defined in an interface. Initially, I considered using the index signature approach, but unfortunately, not all methods have the same signature. My objective is to preserve all type information.
The current basic code does not compile because not all methods are implemented. When I introduce Partial
, it compiles successfully, but it seems like I lose the type information.
import anotherLib from "anotherLib";
interface IALotOfMethods<T> {
methodA(): T;
methodB(opts: MyOpts): T;
...
}
interface IMyClass<T> extends IALotOfMethods<T> {
getName(): string;
getSomething(): number;
}
class MyClass implements IMyClass<MyClass> {
results: any[] = [];
getName(): string {
return "A Name";
}
getSomething(): number {
return 0;
}
}
const aLotOfMethodsList = ['methodA', 'methodB', ...];
aLotOfMethodsList.forEach(funcName => {
MyClass.prototype[funcName] = function(opts: any) {
this.results.push(anotherLib[funcName](opts));
return this;
}
})
const myObj = new MyClass();
myObj.methodA(); // methodA should be available/autosuggested
Is there a way to achieve this? Do I have to manually implement all methods even though they have similar structures? Will I need to sacrifice type information?
Thank you.