Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

148
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda