Home > Mobile >  How to refactor ternarny operator
How to refactor ternarny operator

Time:12-02

I have format = fromNow ? '' : 'LLL'
I saw somewhere that it can be used like that format = fromNow && 'LLL', which i thought means =
if fromNow is true then 'LLL' else nothing but I get an error

Type 'string | boolean' is not assignable to type 'string'. Type 'boolean' is not assignable to type 'string'

CodePudding user response:

which i thought means = if fromNow is true then 'LLL' else nothing

That's not what it means. x && y means:

  1. Evaluate x
  2. If the value from Step 1 is falsy, take that value as the result of the && operation and stop
  3. If the value from Step 1 is truthy, evaluate y and take that value as the result of the && operation

So if your fromNow is a boolean, fromNow && 'LLL' results in either false or 'LLL' — that is, a boolean or a string. But apparently your format variable is declared as type string, so TypeScript won't let you assign a boolean to it.

Your original, using the conditional operator,¹ is preferable if you want a string result either way. You could do fromNow && 'LLL' || '' but that's getting a bit convoluted, whereas the conditional operator version is simple and clear.


¹ The proper name of the ? : operator is the conditional operator. It's a ternary operator (an operator accepting three operands, just like a binary operator accepts two and a unary operator accepts one), and for now it's JavaScript's only ternary operator, but that could change. :-)

  • Related