如何动态调用类方法



我正在尝试用方法callAction创建一个抽象类,该方法动态调用类的方法。

我试着写这篇文章,但我错了。

abstract export class BaseContoller {
public callAction(method: keyof typeof this, parameters: any[]) {
this[method](parameters);
}
}

错误-此表达式不可调用。类型"未知"没有呼叫签名。ts(2349(

有其他方法可以做到这一点吗?

您的类可以同时具有值和函数属性,因此为了确保您的属性是函数类型,您可以使用typeof x === "function"

这有助于在方法执行之前使用调用签名检查method的类型。

class BaseContoller {
public callAction(method: keyof typeof this, parameters: any[]) {
const property = this[method]
if(typeof property === "function") {
property(parameters);
}
}
public testFunction() {}
}

游乐场

我认为静态代码验证不可能在编译时知道所涉及的子类。因此,除非您完全放弃类型检查并首先将this强制转换为any,否则您无法做到这一点。

相反,如果您想要Typescript的类型检查的好处,我认为您将不得不接受其他代码直接调用您的子类方法。

在运行时断言类型安全性可能更明智。

最新更新