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