Proper way to declare with Zod

hi guys, Noob question: Is it better to: A) create types and then check them with zod? or B) better to create Zod objects and then infer types from them? I think i would prefer to do A since it appears cleaner to me, but i also dont see them doing it like this in the docs, so i wonder why?
//A - Types first
type AThing = { thing: string };
const A: AThing = { thing: "A" };
const ASchema = z.infer(AThing);
const AisValid = !!ASchema.parse(A);

//B - Zod first
const BSchema = z.object({ thing: z.string() });
type BThing = z.infer<typeof B>
const B: BThing = { thing: "B" };
const BisValid = !!BSchema.parse(B)
//A - Types first
type AThing = { thing: string };
const A: AThing = { thing: "A" };
const ASchema = z.infer(AThing);
const AisValid = !!ASchema.parse(A);

//B - Zod first
const BSchema = z.object({ thing: z.string() });
type BThing = z.infer<typeof B>
const B: BThing = { thing: "B" };
const BisValid = !!BSchema.parse(B)
2 Replies
Vincent Udén
Vincent Udén2y ago
Zod schemas can include a lot more information than you'd be able to provide with just one example of an object.
const schema = z.object({
thing: z.string().email().min(5),
otherThing: z.string().nullish(),
})
const schema = z.object({
thing: z.string().email().min(5),
otherThing: z.string().nullish(),
})
For example this declares that thing must match an email regex and be at least 5 chars long. While otherThing must be a string | null | undefined
fotoflo
fotoflo2y ago
Thank you! Agreed - the draw back is harder to incrementally adopt but this will be better
Want results from more Discord servers?
Add your server