Home > OS >  How can I call class methods dynamically?
How can I call class methods dynamically?

Time:10-31

I m trying to make an abstract class with method callAction which calls methods of class dynamically.

I tried to write this but I m getting error.

abstract export class BaseContoller {
    public callAction(method: keyof typeof this, parameters: any[]) {
        this[method](parameters);
    }
}

Error - This expression is not callable. Type 'unknown' has no call signatures.ts(2349)

Is there another way to achive this?

CodePudding user response:

Your class can have value as well as function properties together, so to make sure your property is a function type, you can use typeof x === "function".

That can help to check method's type with the call signature before method execution.

class BaseContoller {
    public callAction(method: keyof typeof this, parameters: any[]) {
      const property = this[method]
      if(typeof property === "function") {
        property(parameters);
      }
    }

    public testFunction() {}
}

Playground

CodePudding user response:

I don't think it's possible for static-code validation to know, at compile time, the subclasses involved. Therefore you can't do that unless you throw away type checking altogether and cast this as any first.

Instead, I think you'll have to settle for other code calling your child class methods directly if you want the benefits of Typescript's type checking.

It might be smarter to assert type safety at run time.

  • Related