Skip to content

Commit

Permalink
feat: add null handling for @default tag (#190)
Browse files Browse the repository at this point in the history
  • Loading branch information
tvillaren committed Dec 7, 2023
1 parent 7c0835b commit 6034727
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 3 deletions.
33 changes: 33 additions & 0 deletions src/core/generateZodSchema.test.ts
Expand Up @@ -1300,6 +1300,39 @@ describe("generateZodSchema", () => {
`);
});

it("should deal with @default null value", () => {
const source = `export interface WithDefaults {
/**
* @default null
*/
nonNullableString: string;
/**
* @default null
*/
nullableString: string | null;
/**
* @default "null"
*/
nonNullableStringWithStringAsDefault: string;
}`;
expect(generate(source)).toMatchInlineSnapshot(`
"export const withDefaultsSchema = z.object({
/**
* @default null
*/
nonNullableString: z.string().nullable().default(null),
/**
* @default null
*/
nullableString: z.string().nullable().default(null),
/**
* @default "null"
*/
nonNullableStringWithStringAsDefault: z.string().default("null")
});"
`);
});

it("should ignore unknown/broken jsdoc format", () => {
const source = `export interface Hero {
/**
Expand Down
10 changes: 7 additions & 3 deletions src/core/jsDocTags.ts
Expand Up @@ -55,7 +55,7 @@ type TagWithError<T> = {
export interface JSDocTagsBase {
minimum?: TagWithError<number>;
maximum?: TagWithError<number>;
default?: number | string | boolean;
default?: number | string | boolean | null;
minLength?: TagWithError<number>;
maxLength?: TagWithError<number>;
format?: TagWithError<BuiltInJSDocFormatsType | CustomJSDocFormatType>;
Expand Down Expand Up @@ -175,7 +175,9 @@ export function getJSDocTags(nodeType: ts.Node, sourceFile: ts.SourceFile) {
jsDocTags[tagName] = { value, errorMessage };
break;
case "default":
if (
if (tag.comment === "null") {
jsDocTags[tagName] = null;
} else if (
tag.comment &&
!tag.comment.includes('"') &&
!Number.isNaN(parseInt(tag.comment))
Expand Down Expand Up @@ -289,7 +291,7 @@ export function jsDocTagToZodProperties(
identifier: "optional",
});
}
if (isNullable) {
if (isNullable || jsDocTags.default === null) {
zodProperties.push({
identifier: "nullable",
});
Expand All @@ -314,6 +316,8 @@ export function jsDocTagToZodProperties(
? [f.createFalse()]
: typeof jsDocTags.default === "number"
? [f.createNumericLiteral(jsDocTags.default)]
: jsDocTags.default === null
? [f.createNull()]
: [f.createStringLiteral(jsDocTags.default)],
});
}
Expand Down

0 comments on commit 6034727

Please sign in to comment.