sveltekit-superforms: zod schema with "refine" results in type error

reproduction:

const schema = z
	.object({
		name: z.string(),
		email: z.string().email(),
		password: z.string().min(8),
		confirmPassword: z.string().min(8)
	})
	.refine((data) => data.password === data.confirmPassword, {
		message: "Passwords don't match",
		path: ['confirmPassword']
	});

export const load = (async (event) => {
	const form = await superValidate(event, schema);

	return {
		form
	};
}) satisfies PageServerLoad;

error: Argument of type ‘ZodEffects<ZodObject<{ name: ZodString; email: ZodString; password: ZodString; confirmPassword: ZodString; }, “strip”, ZodTypeAny, { name: string; email: string; password: string; confirmPassword: string; }, { …; }>, { …; }, { …; }>’ is not assignable to parameter of type ‘AnyZodObject’. Type ‘ZodEffects<ZodObject<{ name: ZodString; email: ZodString; password: ZodString; confirmPassword: ZodString; }, “strip”, ZodTypeAny, { name: string; email: string; password: string; confirmPassword: string; }, { …; }>, { …; }, { …; }>’ is missing the following properties from type ‘ZodObject<any, any, any, { [x: string]: any; }, { [x: string]: any; }>’: _cached, _getCached, shape, strict, and 14 more.ts(2345)

is this intentional?

About this issue

  • Original URL
  • State: closed
  • Created a year ago
  • Reactions: 5
  • Comments: 15 (10 by maintainers)

Most upvoted comments

Thank you for reporting, I haven’t considered using refine on the whole object, that’s why it fails. I have to investigate if the type inference can handle extracting the ZodObject from the ZodEffects and still be compatible with the Validation<T> type.

In the meantime, I’d instead use setError to handle your case:

import { setError, superValidate } from 'sveltekit-superforms'

export const load = (async (event) => {
  const form = await superValidate(event, schema);

  if(form.data.password !== form.data.confirmPassword) {
    return setError(form, 'confirmPassword', "Passwords don't match");
  }

  return { form };
}) satisfies PageServerLoad;

Closing this, as the tests are working fine.

Glad to hear that 😃 I just noticed that the setError check should of course be in the form action, not in the load function.