How to make Object Properties flexible with Zod?

  Kiến thức lập trình

New to Typescript, Zod & Trpc.

Say I have a schema for both animals & plants. I want to store all their common properties in the “root” of the schema and then put the more specific properties into a sub-object called custom. (just a made-up example to simplify things)

So far I have this:

create: t.procedure
    .input(z.object({
      id: z.string(),
      type: z.string(), //can be "ANIMAL" or "PLANT"
      //all other common properties go here
      //...
      custom: z.object({ fur: z.string() }) //...if it's an animal, it will have "fur" here, if it's a plant something entirely different, like "seeds"
    }).nullish())

I don’t understand how to get this to work, or how I would accomplish this with zod. I looked into zods discriminated union, but I don’t seem to fully understand how the syntax works?

LEAVE A COMMENT