PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, November 14, 2022

[FIXED] How can I call class methods dynamically?

 November 14, 2022     abstract-class, error-handling, methods, oop, typescript     No comments   

Issue

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

I have tried to write this but I am 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?


Solution

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



Answered By - Nick Vu
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing