Home > Software design >  Call function from a string name
Call function from a string name

Time:08-30

I am trying to call an Angular function with the function's string name but angular is throwing an error.

const functionName = 'getFilelist';
if (this[functionName]) {
  this[functionName]();
}

enter image description here

CodePudding user response:

You should be able to use a type assertion here so TypeScript knows that the key you are calling is on the object you are trying to index.

For example, this[functionName as keyof typeof ApplicationFormComponent]. This should tell TypeScript you are accessing a proper element on the class.

CodePudding user response:

The following code snippet should work. Just declare the type of functionName as keyof ApplicationFormComponent.

test() {
  const functionName: keyof ApplicationFormComponent = 'getFilelist';
  if (this[functionName]) {
    this[functionName]();
  }
}
  • Related