colinhacks / zod

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

Generic type function converting property with a default value to optional #3579

Open jashiels99 opened 4 months ago

jashiels99 commented 4 months ago

I have written a helper function that allows me to validate FormData objects using Zod. Since this can be used for various schemas, I have used a generic type.

The problem I'm having is, when using the helper function it seems to be turning the properties with default values set in the schemas to optional:

export const createUserSchema = z.object({
    name: fullName(),
    email: email(),
    sendEmail: z.boolean().default(true)
});

Screenshot 2024-06-17 at 15 39 38

Here is the code for the validate helper function:

export function validate<T>(
    formData: FormData,
    schema: z.ZodSchema<T>
): { validatedData: T; errors: null } | { validatedData: null; errors: ActionErrors<T> } {
    const body = parseFormData(formData);
    const validated = schema.safeParse(body);

    if (!validated.success) {
        return {
            validatedData: null,
            errors: formatZodErrors<T>(validated.error),
        };
    }

    return { validatedData: validated.data, errors: null };
}

The fact this is being returned with an optional property just doesn't make any sense to me. Any explanation or help would be much appreciated 😊.

Worth noting that if I don't run this through the helper function and parse it directly in the action, it isn't returning as optional which you would expect.

BenjaminLindberg commented 3 months ago

+1