【问题标题】:Typescript: dynamically calling method/function打字稿:动态调用方法/函数
【发布时间】:2023-02-10 16:10:06
【问题描述】:
class Foo {
    methodA(){}

    methodB(){}

    runMethod(methodName: string) {
       /**
        * need to call method dynamically from inheritance method 
        * but it give error something like This expression is not callable
        * Type `unknown` has no call signatures.
       **/
       this[methodName]()
    }
}

如何让它通过打字稿。如果通过输入 // @ts-ignore 告诉打字稿忽略该行,它会起作用,但我想知道这样做的正确方法。

【问题讨论】:

    标签: typescript


    【解决方案1】:

    TypeScript 需要知道 methodName"methodA""methodB",它不能完全是其他东西。

    做到这一点的简单方法是使用字符串文字联合:

    class Foo {
        methodA() {}
    
        methodB() {}
    
        runMethod(methodName: "methodA" | "methodB") {
           this[methodName]()
        }
    }
    

    Playground example

    【讨论】:

      猜你喜欢
      • 2021-09-10
      • 1970-01-01
      • 1970-01-01
      • 2019-11-15
      • 2016-02-18
      • 2016-10-26
      • 2021-06-05
      • 1970-01-01
      • 2017-02-25
      相关资源
      最近更新 更多