Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 951
Colum Avatar asked Jun 29 '16 12:06

Colum


2 Answers

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!

like image 168
ptim Avatar answered Nov 03 '22 20:11

ptim


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]();
like image 14
Radim Köhler Avatar answered Nov 03 '22 19:11

Radim Köhler