Is using zod for type narrowing fine solution?

Is using parse for type narrowing good idea with decent performance or should I make validation functions for objects?
let a = await dbDrizzle.query.document.findFirst({
with: {
lines: true
},
}).then(r => {
if (!r) throw new Error('Document not found')
if (r.typ === 'order') {
const lineSchema = orderLineSchema
return orderSchema.extend({lines: z.array(lineSchema)}).parse(r)
} else if (r.typ === 'receipt') {
const lineSchema = receiptLineSchema
return receiptSchema.extend({lines: z.array(lineSchema)}).parse(r)
}
})
let a = await dbDrizzle.query.document.findFirst({
with: {
lines: true
},
}).then(r => {
if (!r) throw new Error('Document not found')
if (r.typ === 'order') {
const lineSchema = orderLineSchema
return orderSchema.extend({lines: z.array(lineSchema)}).parse(r)
} else if (r.typ === 'receipt') {
const lineSchema = receiptLineSchema
return receiptSchema.extend({lines: z.array(lineSchema)}).parse(r)
}
})
1 Reply
Michael Schaufelberger
If you generally trust the data that's coming from your db, you can safely use e.g. type predicates to narrow the data further. This should usually be faster. But if you always have only a small dataset to check, use whatever gives the best DX imo.
Want results from more Discord servers?
Add your server