Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

144
Views
How to choose method to call depending on argument

The problem

I have a method foo(msg: string, arg: string) which will call a method from bar, which is an object in the same class as foo. Which method depends on the value of arg. My problem is how I should do that in a good way.

In my real code base, I want to use it for refactoring. Because it looks like this:

add() { foo('Adding', 'add'); }
sub() { foo('Subtracting', 'sub'); }
mul() { foo('Multiplying', 'mul'); }
div() { foo('Dividing', 'div'); }

My approach

I have a method like this:

foo(msg: string, arg: string) {
    console.log(msg);
    this.bar[arg]();
    // More code
}

In other words, I want to call the method arg from bar. And this works as it should. However, I would like to restrict the values that arg can have. I suppose I could do something like:

foo(arg: string) {
    if(arg !== 'fun1' && arg !== 'fun2') {
        // Handle error
    }

    this.bar[arg]();
}

The argument arg will never be "constructed". I use constant values directly all the time, like

foo('fun1');

and never something like

// Example of how I will NOT use this
let arg = someFunctionReturningAString();
foo(arg);

My concerns here are 1) safety and people saying "NOOOOO! That's bad practice!" and 2) that my IDE cannot detect spelling errors with my approach.

So my goal here is a convenient method to call a method from bar depending on the argument arg. Preferably something that makes an IDE capable of detecting spelling errors. How do I do that?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You could use literal types in your signature, like:

foo(msg: string, arg: 'add' | 'sub' | 'mul' | 'div') {
    console.log(msg);
    this.bar[arg]();
    // More code
}

https://www.typescriptlang.org/docs/handbook/literal-types.html

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!