Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to refactor ternarny operator

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’

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading