简体   繁体   English

"动态访问 TypeScript 类的方法"

[英]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.我正在尝试使用先前在 TypeScript 中设置的变量的值动态访问类的方法。

Something similar to this:与此类似的东西:

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...我相信一个界面<\/a>会在这里对您进行分类...

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]()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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