From 30de68e2c0ff7841eecd2929410fb1f3d28380e8 Mon Sep 17 00:00:00 2001 From: Akira HIGUCHI Date: Sun, 29 Dec 2024 22:48:54 +0900 Subject: [PATCH] fix: return value for nullish schema --- package.json | 4 ++-- src/index.spec.ts | 32 +++++++++++++++++++++++--------- src/index.ts | 9 ++++----- 3 files changed, 29 insertions(+), 16 deletions(-) diff --git a/package.json b/package.json index 55fac49..4b643c5 100644 --- a/package.json +++ b/package.json @@ -56,8 +56,8 @@ "zod": "^3.24.1" }, "peerDependencies": { - "zod": "3.x", - "typescript": "5.x" + "typescript": "5.x", + "zod": "3.x" }, "packemon": [ { diff --git a/src/index.spec.ts b/src/index.spec.ts index c9a5a29..260d502 100644 --- a/src/index.spec.ts +++ b/src/index.spec.ts @@ -215,16 +215,30 @@ describe("make empty", () => { expect(empty(schema)).toBeNull(); }); - it("nullable", () => { - const schema = z.string().nullable(); - expect(init(schema)).toBeNull(); - expect(empty(schema)).toBeNull(); + describe("nullable", () => { + it("string", () => { + const schema = z.string().nullable(); + expect(init(schema)).toBe(""); + expect(empty(schema)).toBeNull(); + }); + it("array", () => { + const schema = z.array(z.string()).nullable(); + expect(init(schema)).toStrictEqual([]); + expect(empty(schema)).toStrictEqual([]); + }); }); - it("nullish", () => { - const schema = z.string().nullish(); - expect(init(schema)).toBeNull(); - expect(empty(schema)).toBeNull(); + describe("nullish", () => { + it("string", () => { + const schema = z.string().nullish(); + expect(init(schema)).toBe(""); + expect(empty(schema)).toBeNull(); + }); + it("array", () => { + const schema = z.array(z.string()).nullish(); + expect(init(schema)).toStrictEqual([]); + expect(empty(schema)).toStrictEqual([]); + }); }); it("any", () => { @@ -235,7 +249,7 @@ describe("make empty", () => { it("optional", () => { const schema = z.string().optional(); - expect(init(schema)).toBeUndefined(); + expect(init(schema)).toBe(""); expect(empty(schema)).toBeNull(); }); diff --git a/src/index.ts b/src/index.ts index 08fa005..f691bc0 100644 --- a/src/index.ts +++ b/src/index.ts @@ -64,10 +64,11 @@ export function init(schema: T): input { case "ZodNaN": return Number.NaN; case "ZodNull": - case "ZodNullable": case "ZodAny": return null; - // case "ZodOptional": + case "ZodNullable": + case "ZodOptional": + return init(def.innerType); // case "ZodUndefined": // case "ZodVoid": // case "ZodUnknown": @@ -81,9 +82,6 @@ export function init(schema: T): input { } export function empty(schema: T): input { - if (schema.isNullable()) { - return null; - } const def = schema._def; switch (def.typeName) { case "ZodObject": { @@ -111,6 +109,7 @@ export function empty(schema: T): input { return Object.assign(empty(def.left) as any, empty(def.right)); case "ZodPipeline": return empty(def.in); + case "ZodNullable": case "ZodOptional": return empty(def.innerType); case "ZodLiteral":