Skip to content

Commit

Permalink
Make safeParse().error a getter
Browse files Browse the repository at this point in the history
  • Loading branch information
colinhacks committed Mar 5, 2023
1 parent 9012dc7 commit 67b981e
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 5 deletions.
12 changes: 10 additions & 2 deletions deno/lib/types.ts
Expand Up @@ -91,8 +91,16 @@ const handleResult = <Input, Output>(
if (!ctx.common.issues.length) {
throw new Error("Validation failed but no issues detected.");
}
const error = new ZodError(ctx.common.issues);
return { success: false, error };

return {
success: false,
get error() {
if ((this as any)._error) return (this as any)._error as Error;
const error = new ZodError(ctx.common.issues);
(this as any)._error = error;
return (this as any)._error;
},
};
}
};

Expand Down
12 changes: 11 additions & 1 deletion playground.ts
@@ -1,2 +1,12 @@
import { z } from "./src";
z;

console.time("parse");
// for (let i = 0; i < 1000000; i++) {
// z.string().safeParse(123);
// }
const result = z.string().safeParse(123);
if (result.success === false) {
console.log(result.error);
console.log(result.error === result.error);
}
console.timeEnd("parse");
12 changes: 10 additions & 2 deletions src/types.ts
Expand Up @@ -91,8 +91,16 @@ const handleResult = <Input, Output>(
if (!ctx.common.issues.length) {
throw new Error("Validation failed but no issues detected.");
}
const error = new ZodError(ctx.common.issues);
return { success: false, error };

return {
success: false,
get error() {
if ((this as any)._error) return (this as any)._error as Error;
const error = new ZodError(ctx.common.issues);
(this as any)._error = error;
return (this as any)._error;
},
};
}
};

Expand Down

0 comments on commit 67b981e

Please sign in to comment.