Is there a way to implement type checking when extending a class with dynamic methods? For example, if you want to add methods to a class based on options provided to the constructor. This is a common scenario in plain JavaScript.
const defaults = {
dynamicMethods: ['method1', 'method2'];
};
class Hello {
constructor(options) {
options.dynamicMethods.forEach(method => this[method] = this.common);
}
private common(...args: any[]) {
// do something.
}
}
const hello = new Hello(defaults);
The code above will work and allow you to call the dynamic methods, but you won't have intellisense support.
One way to address this issue is with the following approach:
class Hello<T> {
constructor(options) {
options.dynamicMethods.forEach(method => this[method] = this.common);
}
private common(...args: any[]) {
// do something.
}
}
interface IMethods {
method1(...args: any[]);
method2(...args: any[]);
}
function Factory<T>(options?): T & Hello<T> {
const hello = new Hello<T>(options);
return hello as T & Hello<T>;
}
To use this:
import { Factory } from './some/path'
const hello = new Factory<IMethods>(defaults);
This approach works, but it would be interesting to explore other possible solutions!