I am facing an issue with the following code snippet:
const productsWithAddonPrice = useMemo(() => {
const addonsPrice = addonsSelected
.map(id => {
if (addons === undefined) { return 0}
return addons.find(addon => addon.id === id).price})
.reduce((a, b) => a + b, 0);
return [...products].map(p => {
const productCopy = { ...p };
productCopy.price += addonsPrice;
return productCopy;
});
}, [addonsSelected, products, addons]);
The code works fine in non-typescript environment and 'addons' is always initialized as an empty array, so it should never be undefined.
function useProductAndAddon(products: any[], addons: AddonType[] = []) {
But I'm getting a typescript error on this line:
return addons.find(addon => addon.id === id).price})
The error says:
Object is possibly 'undefined'.ts(2532)
This seems incorrect since I'm already checking for undefined on the line above it:
if (addons === undefined) { return 0}
This issue appears to be related to Typescript can't tell I'm returning early if param is undefined. However, I'm struggling to find a solution. Any clarification or guidance on this matter would be greatly appreciated.