Patolord
Patolord•7mo ago

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?
No description
No description
2 Replies
lee
lee•7mo ago
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:
if (movement.fromWarehouseId !== undefined) {
const q = ctx.db.query("inventories").withIndex("by_warehouse_material", (q) => q.eq("warehouseId", movement.warehouseId));
// the query has been constructed but not run yet
// movement.warehouseId is mutable and its type allows undefined, so you can do this
movement.warehouseId = undefined;
// this evaluates the q.eq("warehouseId", movement.warehouseId) which compares a required field to undefined, which is a type error.
const result = await q.unique();
}
if (movement.fromWarehouseId !== undefined) {
const q = ctx.db.query("inventories").withIndex("by_warehouse_material", (q) => q.eq("warehouseId", movement.warehouseId));
// the query has been constructed but not run yet
// movement.warehouseId is mutable and its type allows undefined, so you can do this
movement.warehouseId = undefined;
// this evaluates the q.eq("warehouseId", movement.warehouseId) which compares a required field to undefined, which is a type error.
const result = await q.unique();
}
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.
Patolord
PatolordOP•7mo ago
Thank you very much 🙂