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: union properties can be optional & nullable #66

Merged
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions src/core/generateZodSchema.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -680,6 +680,45 @@ describe("generateZodSchema", () => {
`);
});

it("should allow nullable on optional properties", () => {
const source = `export interface A {
a?: number | null;
}
`;

expect(generate(source)).toMatchInlineSnapshot(`
"export const aSchema = z.object({
a: z.number().optional().nullable()
});"
`);
});

it("should allow nullable on union properties", () => {
const source = `export interface A {
a: number | string | null;
}
`;

expect(generate(source)).toMatchInlineSnapshot(`
"export const aSchema = z.object({
a: z.union([z.number(), z.string()]).nullable()
});"
`);
});

it("should allow nullable on optional union properties", () => {
const source = `export interface A {
a?: number | string | null;
}
`;

expect(generate(source)).toMatchInlineSnapshot(`
"export const aSchema = z.object({
a: z.union([z.number(), z.string()]).optional().nullable()
});"
`);
});

it("should deal with @default with all types", () => {
const source = `export interface WithDefaults {
/**
Expand Down
10 changes: 9 additions & 1 deletion src/core/generateZodSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -439,7 +439,7 @@ function buildZodPrimitive({
return buildZodPrimitive({
z,
typeNode: nodes[0],
isOptional: false,
isOptional,
isNullable: hasNull,
jsDocTags,
sourceFile,
Expand All @@ -462,6 +462,14 @@ function buildZodPrimitive({
skipParseJSDoc,
})
);

// Handling null value outside of the union type
if (hasNull) {
zodProperties.push({
identifier: "nullable",
});
}

return buildZodSchema(
z,
"union",
Expand Down