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 */ 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; }