13

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

2 Answers 2

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]();
Sign up to request clarification or add additional context in comments.

1 Comment

That's awesome! In addition, if you're calling a method from within a class its this[methodName]();
1

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 😊

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

I'm reading this as "I know what the class methods are at compile time"; if you're actually trying to generate class methods at runtime, maybe the voodoo in https://stackoverflow.com/a/46259904/2586761 might help!

1 Comment

I know this is an old question - that's what the necromancer badge is for! 😆

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.