Home > Software design >  How to define function conditionally
How to define function conditionally

Time:05-17

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.

CodePudding user response:

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

  • Related