15

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)

gives me this error...

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]

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

dcsan
  • 11,333
  • 15
  • 77
  • 118

1 Answers1

12

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
    }
}

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.

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
    }
}

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)

Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357
  • interesting so the TS compiler is doing some guesses into the code, esp if you have strings hardwired into your code. I had some real problems with exporting enums from definition files... so types I will try. – dcsan Jul 11 '19 at 14:24
  • @dcsan typescript has support for string literal types. So `"A"` can be a value if used in an expression or a type when used in a type annotation. – Titian Cernicova-Dragomir Jul 11 '19 at 14:29
  • right yes `type` works, but `enum`s don't work within types.d.ts files... – dcsan Jul 11 '19 at 14:30