From 42c5d7f859c76d7d9590184409a944dc1f7368aa Mon Sep 17 00:00:00 2001 From: tvillaren Date: Wed, 24 May 2023 11:40:47 +0200 Subject: [PATCH 1/2] test: failing test cases --- src/core/generateZodSchema.test.ts | 38 +++++++++++++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/src/core/generateZodSchema.test.ts b/src/core/generateZodSchema.test.ts index 229b61a..b9a9e51 100644 --- a/src/core/generateZodSchema.test.ts +++ b/src/core/generateZodSchema.test.ts @@ -870,7 +870,7 @@ describe("generateZodSchema", () => { `); }); - it("should generate add strict() validation when @strict is used on subtype", () => { + it("should add strict() validation when @strict is used on subtype", () => { const source = `export interface A { /** @strict */ a: { @@ -888,6 +888,42 @@ describe("generateZodSchema", () => { `); }); + it("should add strict() before optional() validation when @strict is used on optional subtype", () => { + const source = `export interface A { + /** @strict */ + a?: { + b: number + } + }`; + + expect(generate(source)).toMatchInlineSnapshot(` + "export const aSchema = z.object({ + /** @strict */ + a: z.object({ + b: z.number() + }).strict().optional() + });" + `); + }); + + it("should add strict() before nullable() validation when @strict is used on nullable subtype", () => { + const source = `export interface A { + /** @strict */ + a: { + b: number + } | null + }`; + + expect(generate(source)).toMatchInlineSnapshot(` + "export const aSchema = z.object({ + /** @strict */ + a: z.object({ + b: z.number() + }).strict().nullable() + });" + `); + }); + it("should deal with nullable", () => { const source = `export interface A { /** @minimum 0 */ From 6769c724bc67a51f4037b245fdb9cdf2b5e079e1 Mon Sep 17 00:00:00 2001 From: tvillaren Date: Wed, 24 May 2023 11:46:02 +0200 Subject: [PATCH 2/2] fix: strict() before nullable() / optional() --- src/core/jsDocTags.ts | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/core/jsDocTags.ts b/src/core/jsDocTags.ts index d0f2a4b..1ab3117 100644 --- a/src/core/jsDocTags.ts +++ b/src/core/jsDocTags.ts @@ -230,6 +230,10 @@ export function jsDocTagToZodProperties( expressions: [f.createRegularExpressionLiteral(`/${jsDocTags.pattern}/`)], }); } + // strict() must be before optional() and nullable() + if (jsDocTags.strict) { + zodProperties.push({ identifier: "strict" }); + } if (isOptional) { zodProperties.push({ identifier: "optional", @@ -263,9 +267,6 @@ export function jsDocTagToZodProperties( : [f.createStringLiteral(jsDocTags.default)], }); } - if (jsDocTags.strict) { - zodProperties.push({ identifier: "strict" }); - } return zodProperties; }