colinhacks / zod

TypeScript-first schema validation with static type inference
https://zod.dev
MIT License
33.95k stars 1.19k forks source link

How to create a generic zod parser factory that gives a picked schema with types? #2887

Open zakia98 opened 1 year ago

zakia98 commented 1 year ago

Hi all,

I'm trying to create a generic zod parser factory that takes a schema and a list of fields that transforms that schema into a picked schema, but I am having an issue where the return type information is filtered out to any.

Here's what I have so far:

    const parseFactory = (schema: z.AnyZodObject) =>  { 
        return <T extends keyof z.infer<typeof schema>>({item, fields}: {item: unknown, fields: T[]}): Pick<z.infer<typeof schema>, T> | undefined=> {
          try {
            const pickedSchema = schema.pick(Object.fromEntries(fields.map(field => [field, true])))
            return pickedSchema.parse(item)
          } catch (error) {
            // error handling
          }
        }
    }

However, in the above, the type of the return is :

    {
        [x: string]: any;
        [x: number]: any;
    }

Any help would be appreciated!

zakia98 commented 12 months ago

Sorry, just wondering if I could bump this?