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

116
Vistas
How to define function conditionally

I want to set a function to the result of a ternary operator (that is returning one of two functions) and then call the result. My code looks like this:

const bar = (x: number) => {
  // do something
}

const foo = (x: number) => {
  // do something else
}

const my_function = condition ? bar : foo;

my_function(x)

but I get a type error that my_function is not a function. Why doesn't this work, and how can I make it work? I have to call this function many times which is why I want to do it like this and not just call conditionally.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

@m-s7's answer works. However, it's kind of messy.

IMHO better to commit something like this to production instead:

const bar = (x: number) => {
  // do something
}

const foo = (x: number) => {
  // do something else
}

const my_function = (x: number) => condition ? bar(x) : foo(x)

Here, you are creating a function in which you pass in the arg and return the result from the correct function based on the condition. It's pretty clean and easy to understand at a glance.

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