Skip to content

Fix types for #753 #755

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

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions zod/src/__tests__/__fixtures__/data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,15 +58,15 @@ export const validData = {
},
],
dateStr: '2020-01-01',
} as any as z.infer<typeof schema>;
} satisfies z.input<typeof schema>;

export const invalidData = {
password: '___',
email: '',
birthYear: 'birthYear',
like: [{ id: 'z' }],
url: 'abc',
} as any as z.infer<typeof schema>;
} as unknown as z.input<typeof schema>;

export const fields: Record<InternalFieldName, Field['_f']> = {
username: {
Expand Down
35 changes: 31 additions & 4 deletions zod/src/__tests__/zod.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { FieldValues, Resolver, SubmitHandler, useForm } from 'react-hook-form';
import { Resolver, SubmitHandler, useForm } from 'react-hook-form';
import { z } from 'zod';
import { zodResolver } from '..';
import { fields, invalidData, schema, validData } from './__fixtures__/data';
Expand Down Expand Up @@ -99,7 +99,7 @@ describe('zodResolver', () => {
const resolver = zodResolver(z.object({ id: z.number() }));

expectTypeOf(resolver).toEqualTypeOf<
Resolver<FieldValues, unknown, { id: number }>
Resolver<{ id: number }, unknown, { id: number }>
>();
});

Expand All @@ -109,7 +109,7 @@ describe('zodResolver', () => {
);

expectTypeOf(resolver).toEqualTypeOf<
Resolver<FieldValues, unknown, { id: string }>
Resolver<{ id: number }, unknown, { id: string }>
>();
});

Expand Down Expand Up @@ -145,7 +145,7 @@ describe('zodResolver', () => {

it('should correctly infer the output type from a Zod schema when different input and output types are specified for the handleSubmit function in useForm', () => {
const { handleSubmit } = useForm<{ id: string }, any, { id: boolean }>({
resolver: zodResolver(z.object({ id: z.boolean() })),
resolver: zodResolver(z.object({ id: z.string().transform((s) => !!s) })),
});

expectTypeOf(handleSubmit).parameter(0).toEqualTypeOf<
Expand All @@ -154,4 +154,31 @@ describe('zodResolver', () => {
}>
>();
});

it('should correctly infer the output type from a zod schema using a transform with schemaOptions.raw', () => {
const resolver1 = zodResolver(
z.object({ id: z.number().transform((val) => String(val)) }),
undefined,
{ raw: true },
);
expectTypeOf(resolver1).toEqualTypeOf<
Resolver<{ id: number }, unknown, { id: number }>
>();

const resolver2 = zodResolver(
z.object({ id: z.number().transform((val) => String(val)) }),
{},
{ raw: false },
);
expectTypeOf(resolver2).toEqualTypeOf<
Resolver<{ id: number }, unknown, { id: string }>
>();

const resolver3 = zodResolver(
z.object({ id: z.number().transform((val) => String(val)) }),
);
expectTypeOf(resolver3).toEqualTypeOf<
Resolver<{ id: number }, unknown, { id: string }>
>();
});
});
55 changes: 31 additions & 24 deletions zod/src/zod.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';
import {
FieldError,
FieldErrors,
FieldValues,
Resolver,
ResolverError,
ResolverSuccess,
appendErrors,
} from 'react-hook-form';
import { ZodError, z } from 'zod';
Expand Down Expand Up @@ -80,17 +81,27 @@ function parseErrorSchema(
* resolver: zodResolver(schema)
* });
*/
export function zodResolver<
Input extends FieldValues,
Context,
Output,
Schema extends z.ZodSchema<Output, any, Input> = z.ZodSchema<
Output,
any,
Input
>,
>(
schema: Schema,
// passing `resolverOptions.raw: false` (or omitting) you get the transformed output type
export function zodResolver<Input extends FieldValues, Context, Output>(
schema: z.ZodSchema<Output, any, Input>,
schemaOptions?: Partial<z.ParseParams>,
resolverOptions?: {
mode?: 'async' | 'sync';
raw?: false;
},
): Resolver<Input, Context, Output>
// passing `resolverOptions.raw: true` you get back the input type
export function zodResolver<Input extends FieldValues, Context, Output>(
schema: z.ZodSchema<Output, any, Input>,
schemaOptions: Partial<z.ParseParams> | undefined,
resolverOptions: {
mode?: 'async' | 'sync';
raw: true;
},
): Resolver<Input, Context, Input>
// implementation
export function zodResolver< Input extends FieldValues, Context, Output>(
schema: z.ZodSchema<Output, any, Input>,
schemaOptions?: Partial<z.ParseParams>,
resolverOptions: {
mode?: 'async' | 'sync';
Expand All @@ -99,24 +110,20 @@ export function zodResolver<
): Resolver<
Input,
Context,
(typeof resolverOptions)['raw'] extends true
? Input
: unknown extends Output
? z.output<Schema>
: Output
Output | Input // consumers never see this type; they only see types from overload signatures
> {
return async (values, _, options) => {
return async (values: Input, _, options) => {
try {
const data = await schema[
resolverOptions.mode === 'sync' ? 'parse' : 'parseAsync'
](values, schemaOptions);
const data = resolverOptions.mode === 'sync'
? schema.parse(values, schemaOptions)
: await schema.parseAsync(values, schemaOptions);

options.shouldUseNativeValidation && validateFieldsNatively({}, options);

return {
errors: {} as FieldErrors,
errors: {},
values: resolverOptions.raw ? Object.assign({}, values) : data,
};
} satisfies ResolverSuccess<Input | Output>;
} catch (error) {
if (isZodError(error)) {
return {
Expand All @@ -129,7 +136,7 @@ export function zodResolver<
),
options,
),
};
} satisfies ResolverError<Input>;
}

throw error;
Expand Down