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

fix: add the formatted type in ZodFormattedError type recursion #3762

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
10 changes: 5 additions & 5 deletions src/ZodError.ts
Original file line number Diff line number Diff line change
Expand Up @@ -177,17 +177,17 @@ export const quotelessJson = (obj: any) => {
return json.replace(/"([^"]+)":/g, "$1:");
};

type recursiveZodFormattedError<T> = T extends [any, ...any[]]
? { [K in keyof T]?: ZodFormattedError<T[K]> }
type recursiveZodFormattedError<T, U = string> = T extends [any, ...any[]]
? { [K in keyof T]?: ZodFormattedError<T[K], U> }
: T extends any[]
? { [k: number]: ZodFormattedError<T[number]> }
? { [k: number]: ZodFormattedError<T[number], U> }
: T extends object
? { [K in keyof T]?: ZodFormattedError<T[K]> }
? { [K in keyof T]?: ZodFormattedError<T[K], U> }
: unknown;

export type ZodFormattedError<T, U = string> = {
_errors: U[];
} & recursiveZodFormattedError<NonNullable<T>>;
} & recursiveZodFormattedError<NonNullable<T>, U>;

export type inferFormattedError<
T extends ZodType<any, any, any>,
Expand Down
13 changes: 10 additions & 3 deletions src/__tests__/error.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -309,9 +309,16 @@ test("formatting", () => {
if (!result2.success) {
type FormattedError = z.inferFormattedError<typeof schema, number>;
const error: FormattedError = result2.error.format(() => 5);
expect(error._errors).toEqual([]);
expect(error.inner?._errors).toEqual([]);
expect(error.inner?.name?._errors).toEqual([5]);

type FormattedErrors = number[] | undefined;
const schemaErrors: FormattedErrors = error._errors;
const innerErrors: FormattedErrors = error.inner?._errors;
// @ts-expect-error it should not be the default formatted type
const nameErrors: string[] | undefined = error.inner?.name?._errors;

expect(schemaErrors).toEqual([]);
expect(innerErrors).toEqual([]);
expect(nameErrors).toEqual([5]);
}
});

Expand Down