-1

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'

RheinmetallSkorpion
  • 383
  • 1
  • 2
  • 11
  • It seems the && returns either the left hand side (bool) or the right hand side (string) but a string is required. You probably need an optional string on the left hand side. – gnasher729 Dec 02 '21 at 07:41

1 Answers1

1

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. :-)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875