Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
jashiels99 opened this issue Jun 17, 2024 · 0 comments

Comments

@jashiels99
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant