How to get rid of this unnecessary code while preventing eslint from complaining.

const index = items.findIndex((i) => i.productID == productID); if (index != -1) { const existingItem = items[index]; if (!existingItem) throw 'item not found'; // this will never happen, but without eslint is complaining existingItem.quantity += quantity;// therefore this should be typesafe items[index] = existingItem } preferably I would like to do this, but then eslint is complaining "object is possibly undefined": const index = items.findIndex((i) => i.productID == productID); if (index != -1) { items[index].quantity += quantity; }
No description
4 Replies
Develliot
Develliot•12mo ago
If you are looking through a small array and returning another small array with changes you are probably better off using .map(). It's less memory efficient but has fewer side effects and removes the possibly undefined errors because you are creating as you loop through. Since find() exists I rarely use findIndex()
dan
dan•12mo ago
items[index]!.quanitiy The ! is the non-null assertion operator, its useful for situations like this where you actually 100% of the time know it will exist, though you may get another eslint error depending on your config.
Xanacas
Xanacas•12mo ago
"Since find() exists I rarely use findIndex()" I didn't realize, that find create a mutable item whose changes are also reflected in the array. amazing 🙂
Develliot
Develliot•12mo ago
In React land we often go out of our way to avoid doing things with side effects and create new arrays rather than mutate the thing we are iterating over.
Want results from more Discord servers?
Add your server