Skip to content

Commit

Permalink
fix: strict() modifier should come before optional/nullable (#137)
Browse files Browse the repository at this point in the history
* test: failing test cases

* fix: strict() before nullable() / optional()

---------

Co-authored-by: tvillaren <tvillaren@users.noreply.github.com>
  • Loading branch information
tvillaren and tvillaren committed May 24, 2023
1 parent 9cb8a3e commit f8be6bd
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 4 deletions.
38 changes: 37 additions & 1 deletion src/core/generateZodSchema.test.ts
Expand Up @@ -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: {
Expand All @@ -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 */
Expand Down
7 changes: 4 additions & 3 deletions src/core/jsDocTags.ts
Expand Up @@ -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",
Expand Down Expand Up @@ -263,9 +267,6 @@ export function jsDocTagToZodProperties(
: [f.createStringLiteral(jsDocTags.default)],
});
}
if (jsDocTags.strict) {
zodProperties.push({ identifier: "strict" });
}

return zodProperties;
}
Expand Down

0 comments on commit f8be6bd

Please sign in to comment.