Imagine having a scenario with the following class:
class Example {
method1 = this.generateDynamicFunction((param: string) => {
return "string" + param;
});
method2 = this.generateDynamicFunction((param: number) => {
return 1 + param;
});
generateDynamicFunction(fn: (param: any) => any) {
return (param) => fn(param);
}
}
const instance = new Example()
instance.method1('text') // => stringtext
instance.method2(5) // => 6
How can I define the types for the functions Example.prototype.method1
and Example.prototype.method2
? I aim to explicitly specify that method1
accepts and returns a string
, while method2
accepts and returns a number
.
Admittedly, this example is somewhat contrived. In my current project, I am in the final stages of revamping one of my message queue client libraries where many class functions are created dynamically. These functions share common functionalities but have varying input and output types.