Home > OS >  Create a function that call methods in a class in typescript
Create a function that call methods in a class in typescript

Time:07-29

normally class method call like

classA.method1(args)

But I want to make it a function which takes methodName and arguments to pass in and return the method result.

const function = (methodName, args = []) => {
  return classA[methodName](...args);
}

there are errors in the above code.

At the end I want to do something like:

function(methodName, [args]) 

to call classA's methodName method and return the result

How to write it in typescript? Thanks

CodePudding user response:

Maybe this can help you start in the right way. The example below is not very typesafe since there is some casting to any

class classA {
  static methodA1() {
    console.log('A1')
  }

  static methodA2(arg: string) {
    console.log(`A2: ${arg}`)
  }
}

const executeFunc = (funcName: string, args: any[] = []) => {
  return (classA as any)[funcName](...args)
}

executeFunc('methodA1')
executeFunc('methodA2', ['input argument!'])

I have a classA class with two methods that I can call in executeFunc

  • Related