Skip to content
Advertisement

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.

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

Advertisement

Answer

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]();
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement