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

Nullish coalescing operator in object not working but ternary does

I have an object that has a selector property which should receive a function callback:

{
  selector: (element) => element.name
}

but I want to conditionally pick another callback function for the selector via the ?? operator from another object:

const extendedCallback = {
  example: (element) => element.another
}

so what I do is:

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

{
  selector: extendedCallback.example ?? (element) => element.name
}

but then my IDE says Cannot find name 'element'.ts(2304) for the right handed side of the operator. When I do the same with ternary:

'example' in extendedCallback ? extendedCallback.example : (element) => element.name

it works fine. What is a misconception I have about the ?? ?

>Solution :

Your problem is operator precedence, => has lower precedence than ?? so your code gets interpreted as

(extendedCallback.example ?? (element)) => element.name

You need to use parentheses to get the correct operation.

selector: extendedCallback.example ?? ((element) => element.name)
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