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:
JavaScript
x
9
1
class Foo {
2
bar(){ }
3
}
4
5
var methodName = "bar";
6
var fooBar = new Foo();
7
8
fooBar.methodName(); // I would like this to resolve to fooBar.bar();
9
For example in PHP I can do the following:
JavaScript
1
9
1
class Foo {
2
public function bar(){ }
3
}
4
5
$methodName = "bar";
6
$fooBar = new Foo();
7
8
$fooBar.$methodName(); // resolves to fooBar.bar();
9
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)
JavaScript
1
2
1
fooBar[methodName]();
2