如何在打字稿中动态调用实例方法? [英] how to dynamically call instance methods in typescript?

查看:51
本文介绍了如何在打字稿中动态调用实例方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象,并且想在其上动态调用一个方法.

I have an object and I want to dynamically call a method on it.

进行类型检查会很不错,但这也许是不可能的.但是我什至无法完全编译它:

Having typechecking would be nice but that maybe impossible. But I can't even get it to compile at all currently:

  const key: string = 'someMethod'
  const func = this[key]
  func(msgIn)

给我这个错误...

Element implicitly has an 'any' type 
because expression of type 'any' can't be used 
to index type 'TixBot'.

我尝试了其他一些类型选择,但没有成功.

I tried some other type options without success.

  const key: any = cmd.func
  const func: any = this[key]

除了 @ ts-ignore 之外,我该如何解决?我想知道是否可以使用 .call() bind 来解决该问题?

Apart from @ts-ignore how could I solve this? I was wondering if I can use .call() or bind to somehow work around it?

推荐答案

如果无法检查所使用的字符串是否是该类的有效成员,则Typescript将出错.例如,这将起作用:

Typescript will error if it can't check that the string used is a valid member of the class. This for example will work:

class MyClass {
    methodA() {
        console.log("A")
    }
    methodB() {
        console.log("B")
    }

    runOne() {
        const random = Math.random() > 0.5 ? "methodA" : "methodB" // random is typed as "methodA" | "methodB"
        this[random](); //ok, since random is always a key of this
    }
}

在上面的示例中,从常量中删除显式类型注释应为您提供文字类型,并允许您使用const索引到 this .

In the samples above removing the explicit type annotation from a constant should give you the literal type and allow you to use the const to index into this.

您也可以将字符串键入为 Classofkey :

You could also type the string as keyof Class :

class MyClass {
    methodA() {
        console.log("A")
    }
    methodB() {
        console.log("B")
    }

    runOne(member: Exclude<keyof MyClass, "runOne">) { // exclude this method
        this[member](); //ok
    }
}

如果您已经有一个 string 使用对MyClass的 key 的断言,尽管这不是安全的类型( this [member as MyOf的keyClass),这也是一个选择] ,其中让成员:字符串)

If you already have a string using an assertion to keyof MyClass is also an option although this is not as type safe (this[member as keyof MyClass] where let member: string)

这篇关于如何在打字稿中动态调用实例方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆