简体   繁体   中英

Dynamically access methods of class TypeScript

I'm trying to access the methods of a class dynamically, using the value of a previously set variable in TypeScript.

class Foo {
    bar(){ }
}

var methodName = "bar";
var fooBar = new Foo();

fooBar.methodName(); // I would like this to resolve to fooBar.bar();

我们只需要离开强类型(和检查)世界,只使用 JavaScript 风格(这仍然很有用,例如在这些情况下)

fooBar[methodName]();

I believe an interface<\/a> will sort you out here...

interface FooInterface {
  bar: () => void
  // ...other methods
}

class Foo implements FooInterface {
  bar() {
    console.log('bar')
  }
  // .. other methods omitted
}

const foo = new Foo()

// good 
foo['bar']

// Element implicitly has an 'any' type because expression of type '"barry"' can't be used to index type 'Foo'.
//  Property 'barry' does not exist on type 'Foo'.
foo['barry']

let method: keyof FooInterface

// good
method = 'bar'
foo[method]()

// Type '"barry"' is not assignable to type 'keyof FooInterface'.
method = 'barry'
foo[method]()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM