0

Just getting used to trpc. Say I have a standard procedure:

update: t.procedure
    .input(z.object({
      id: z.string(),
      type: z.string(),
      content: z.object({ title: z.string() }).nullish()
    }).nullish())

Now what I am interested in is the content attribute. In my mysql schema, that content field is a JSON field. Depending on the type field, it will contain different values.

For example. If type is blogPost, it will contain attributes like title & category, but if the type is set to landingPage those attributes will change. (just an example to make it more straightforward, my use case isn't about blogPosts etc.)

As far as I understand, I can solve this with discriminatedUnion:

z.discriminatedUnion("type", [
    z.object({ type: z.literal("a"), a: z.string() }),
    z.object({ type: z.literal("b"), b: z.string() }),
  ])
  .parse({ type: "a", a: "abc" });

but i am not sure how to apply this to my case? I want it to only apply to the content field and keep the other attributes the same.

antonwilhelm
  • 5,768
  • 4
  • 19
  • 45
  • The `z.object` schema takes arbitrary schemas for each of it's keys. You could put the `discriminatedUnion` as the value for `content` in the same way that you put `z.string()` as the value for `id`. – Souperman Nov 01 '22 at 14:04
  • Thanks a lot. I guess I don't really understand the syntax here with `"type"` - what exactly does this refer to? How would I turn my content object into a discriminated union? Sorry, I feel stuck. – antonwilhelm Nov 04 '22 at 16:10
  • No worries, I agree the api is a little confusing. When you use `discriminatedUnion` you tell `zod` about a list of types that the union has in it. In order for `TypeScript` to tell which variant is which, one of the fields must be shared between each of the types with a unique value in each case. The `"type"` string is the name of that field. In the example you showed you named that field `type` so you pass in the string `"type"` to tell zod about that. Notice you have a unique literal value stored under `type` in each branch. – Souperman Nov 05 '22 at 00:24

0 Answers0