Query withIndex cannot be undefined?
I was using filter query and it worked fine. but i changed to withIndex and now VS Code complains movement.fromWarehouseId might be an Id or Undefined.
putting a ! ends the problem but is this the correct way?
2 Replies
The exclamation point seems fine to me. this is a things with dynamically typed languages. It's happening because
movement.fromWarehouseId
is mutable, so it could potentially change by the time the withIndex
callback is called. In other words, the type system can't be sure you won't do this:
You can get around it by defining const fromWarehouseId = movement.fromWarehouseId
at the beginning of the function. Then when you check if (fromWarehouseId !== undefined)
it knows that fromWarehouseId
isn't undefined, and since it's const it will still be not-undefined even if it gets captured by the withIndex
callback and executed later.Thank you very much 🙂