RJ
RJ2y ago

Cannot query with sum type variant index

Say I have
// convex/schema.ts

export default defineSchema({
pets: defineTable(
v.union(
v.object({
tag: v.literal("Dog"),
favoriteToy: v.optional(v.string())
}),
v.object({
tag: v.literal("Cat")
})
)
)
.index("by_favorite_toy", ["favoriteToy"]),
})
// convex/schema.ts

export default defineSchema({
pets: defineTable(
v.union(
v.object({
tag: v.literal("Dog"),
favoriteToy: v.optional(v.string())
}),
v.object({
tag: v.literal("Cat")
})
)
)
.index("by_favorite_toy", ["favoriteToy"]),
})
This works, but trying to query using that index fails with a type error
db
.query("orders")
.withIndex("by_favorite_toy", (q) =>
q.eq("favoriteToy", favorite_toy)
)
.unique()
db
.query("orders")
.withIndex("by_favorite_toy", (q) =>
q.eq("favoriteToy", favorite_toy)
)
.unique()
error TS2345: Argument of type 'string' is not assignable to parameter of type 'undefined'.

q.eq("favoriteToy", favoriteToy),
~~~~~~~~~~~
error TS2345: Argument of type 'string' is not assignable to parameter of type 'undefined'.

q.eq("favoriteToy", favoriteToy),
~~~~~~~~~~~
I expected the above to work as though the following were true (though the following is not valid)
// convex/schema.ts

export default defineSchema({
pets: defineTable(
v.union(
v.object({
tag: v.literal("Dog"),
favoriteToy: v.optional(v.string())
}),
v.object({
tag: v.literal("Cat"),
favoriteToy: v.literal(undefined) // `undefined` not an accepted literal
})
)
)
.index("by_favorite_toy", ["favoriteToy"]),
})
// convex/schema.ts

export default defineSchema({
pets: defineTable(
v.union(
v.object({
tag: v.literal("Dog"),
favoriteToy: v.optional(v.string())
}),
v.object({
tag: v.literal("Cat"),
favoriteToy: v.literal(undefined) // `undefined` not an accepted literal
})
)
)
.index("by_favorite_toy", ["favoriteToy"]),
})
So I found this somewhat surprising.
4 Replies
sshader
sshader2y ago
Yeah this seems like an issue in our types, and I'm trying out a fix for this -- thanks for reporting. Also to be clear, I believe this is just an issue with the types and the query is valid and should behave as expected? (if we put a // @ts-expect-error or casted to get around the type issue?)
RJ
RJOP2y ago
Yes, this is just a typing issue! Tested and confirmed that the query is otherwise valid and behaves as expected.
sshader
sshader2y ago
I think this typing issue is fixed in convex 1.1!
RJ
RJOP2y ago
Thank you @sshader, I'll report here when I get a chance to test it out! Upgraded and I no longer see a type error, thanks again!

Did you find this page helpful?