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

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

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 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