Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

141
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda