sanity-typed-schema-builder icon indicating copy to clipboard operation
sanity-typed-schema-builder copied to clipboard

Possible to pick/omit?

Open Kolby-Udacity opened this issue 1 year ago • 8 comments

Hi, I'm trying to utilize my existing sanity-typed-schema-builder document to create a new Zod document. I want to pick fields from the former to add to the latter. Is this possible somehow?

Example:

export const programSanitySchema = s.document({
  name: 'program',
  title: 'Program',
  fields: [
    {
      name: 'title',
      title: 'Title',
      description: 'The title of the program',
      type: s.string(),
    },
    {
      name: 'description',
      title: 'Description',
      description: 'The description of the program',
      type: s.string(),
    }
  ],
});

export const programPreviewZodSchema = z.object({
  title: programSanitySchema.pick({title: true})
});

Thanks

Kolby-Udacity avatar Apr 11 '23 16:04 Kolby-Udacity

const zodOfDocument: ZodType = s.document({ ... }).zod;

// Do what you want with zodOfDocument

saiichihashimoto avatar Apr 11 '23 16:04 saiichihashimoto

const zodOfDocument: ZodType = s.document({ ... }).zod;

// Do what you want with zodOfDocument

Thanks, I tried that, but TypeScript says:

Property 'pick' does not exist on type ZodType ...

Kolby-Udacity avatar Apr 11 '23 17:04 Kolby-Udacity

can you show me a repro? Your code snippet has programSanitySchema.pick({title: true}) which is incorrect.

saiichihashimoto avatar Apr 11 '23 18:04 saiichihashimoto

Here is a codesandbox: https://codesandbox.io/s/silent-thunder-7pg960?file=/src/App.tsx

image

Kolby-Udacity avatar Apr 11 '23 19:04 Kolby-Udacity

ah, I see. the object returned is of type ZodType, not ZodObject, so it doesn't have the object specific methods. I think that's a change we can make!

saiichihashimoto avatar Apr 11 '23 20:04 saiichihashimoto

That would be great, thank you. Awesome library btw!

Kolby-Udacity avatar Apr 11 '23 20:04 Kolby-Udacity

FYI until we fix it, you should just be able to cast it into a ZodObject. I think it actually is a ZodObject so this shouldn’t be an issue.

saiichihashimoto avatar Apr 15 '23 20:04 saiichihashimoto

Yeah I actually tried that for awhile the other day. I settled on using as ZodObject<any>, which works, but doesn't give me the options when I use pick. Not a huge problem while I wait for a fix, but I'm curious if there is a way to fix this. Seems the only way (other than recreating a Zod object) is as ZodObject<programSchema.zod>, but that obviously doesnt work because if it did none of this would be a problem lol

Kolby-Udacity avatar Apr 16 '23 17:04 Kolby-Udacity