有没有人在使用动态方法扩展类时获得类型检查的好方法?例如,假设您想使用基于传递给构造函数的选项的方法来扩展类。这在普通的 JavaScript 中很常见。
const defaults = {
dynamicMethods: ['method1', 'method2'];
};
class Hello {
constructor(options) {
options.dynamicMethods.forEach(m => this[m] = this.common);
}
private common(...args: any[]) {
// do something.
}
}
const hello = new Hello(defaults);
Run Code Online (Sandbox Code Playgroud)
当然,上面的方法会起作用,您将能够调用这些动态方法,但不会获得智能感知。
不是你可以用下面的东西来解决这个问题:
class Hello<T> {
constructor(options) {
options.dynamicMethods.forEach(m => this[m] = 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 …Run Code Online (Sandbox Code Playgroud) typescript ×1