最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Dynamically access methods of class TypeScript - Stack Overflow

programmeradmin2浏览0评论

I'm trying to access the methods of a class dynamically, using the value of a previously set variable in 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();

For example in PHP I can do the following:

class Foo {
    public function bar(){ }
}

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

$fooBar.$methodName(); // resolves to fooBar.bar();

Anyone know if this is possible, and if it is, how to do it? I know it slightly contradicts the idea of a typed language, but its the only solution to my current problem

I'm trying to access the methods of a class dynamically, using the value of a previously set variable in 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();

For example in PHP I can do the following:

class Foo {
    public function bar(){ }
}

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

$fooBar.$methodName(); // resolves to fooBar.bar();

Anyone know if this is possible, and if it is, how to do it? I know it slightly contradicts the idea of a typed language, but its the only solution to my current problem

Share Improve this question edited Jul 6, 2020 at 18:46 Martijn Pieters 1.1m320 gold badges4.2k silver badges3.4k bronze badges asked Jun 29, 2016 at 12:47 ColumColum 9862 gold badges9 silver badges23 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 16

We simply have to leave strongly typed (and checked) world, and use just a JavaScript style (which is still useful, e.g. in these cases)

fooBar[methodName]();

I believe an interface 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]()

You can play with this example in the Typescript Playground.

I'm learning in public here, so hopefully someone might refine this further one day

发布评论

评论列表(0)

  1. 暂无评论