Next.js Discord

Discord Forum

Zod schema

Unanswered
Prairie yellowjacket posted this in #help-forum
Open in Discord
Avatar
Prairie yellowjacketOP
I have an array of objects in zod schema, I want to make service field required when type === "service" and I want to make richText field required when type === "richText", does anyone have an idea how to do that?
descriptions: z.array(
   z
      .object({
        type: z.string(),
        service: z.string(),
        richText: z.string(),
      })
    ),

2 Replies

Avatar
joulev
something like this?
z.array(
  z.object({
    type: z.literal("service"),
    service: z.string().min(1),
  }).or(z.object({
    type: z.literal("richText"),
    richText: z.string().min(1),
  }))
)

the ts type will be
({ type: "service", service: string } | ( type: "richText", richText: string })[]
Avatar
Prairie yellowjacketOP
That looks good, I’ll try it, I managed to do it with refine but this seems so much simpler