ian
ian13mo ago

Want branded strings or more specific

Want branded strings or more specific types? I just realized this just works:
defineSchema({
myTable: defineTable({
myField: v.string() as Validator<MyStringType>
})
)}
defineSchema({
myTable: defineTable({
myField: v.string() as Validator<MyStringType>
})
)}
myField will be typed as MyStringType when you get it from the DB, and give you errors on functions like withIndex if your parameter isn't MyStringType when comparing against myField Note: this isn't runtime validation, this is just type annotations to help you catch bugs & be more descriptive.
3 Replies
wjarjoui
wjarjoui13mo ago
This looks super cool! Can you elaborate on what MyStringType could look like?
ian
ianOP13mo ago
export type MyStringType = string & { __myStringType: never }; Better yet, here's a little article on it I just wrote for you: https://stack.convex.dev/using-branded-types-in-validators
Using branded types in validators
If you have a more specific type than what you can express with Convex validators, you can still document that at the type level in Convex by casting ...

Did you find this page helpful?