Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Fix] strict() modifier should come before optional/nullable #137

Merged
merged 2 commits into from
May 24, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
38 changes: 37 additions & 1 deletion src/core/generateZodSchema.test.ts
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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