Skip to content

Commit

Permalink
fix: default method for function schema.
Browse files Browse the repository at this point in the history
  • Loading branch information
Akira Higuchi committed Aug 5, 2022
1 parent 1ff8d2d commit fa98db3
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 5 deletions.
20 changes: 16 additions & 4 deletions src/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,11 +129,23 @@ describe("make empty", () => {
expect(init(z.string().default("default value"))).toBe("default value");
expect(init(z.number().default(2))).toBe(2);
expect(init(z.boolean().default(true))).toBe(true);
expect(init(z.null().default(null))).toBeNull();
expect(init(z.any().default({ default: true }))).toEqual({ default: true });

// return value not strict equal to default parameter.
const defaultValue = { default: true };
expect(init(z.any().default(defaultValue))).toEqual({ default: true });
expect(init(z.any().default(defaultValue)) === defaultValue).toBe(false);
const defaultFunction = (s: string) => s?.length;
expect(
init(
z
.function()
.args(z.string())
.returns(z.number())
.default(() => defaultFunction)
)
).toBe(defaultFunction);

// return value for object/array/set/map not strict equal to default parameter.
const defaultObject = { default: true };
expect(init(z.any().default(defaultObject)) === defaultObject).toBe(false);
});

it("nan", () => {
Expand Down
4 changes: 3 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,9 @@ function make<T extends ZodTypeAny>(schema: T): unknown {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
return (..._: any[]) => make(def.returns);
case "ZodDefault":
return clone(def.defaultValue());
return def.innerType._def.typeName === "ZodFunction"
? def.defaultValue()
: clone(def.defaultValue());
case "ZodNaN":
return NaN;
case "ZodNull":
Expand Down

0 comments on commit fa98db3

Please sign in to comment.