Skip to content

Commit

Permalink
fix: union properties can be optional & nullable (#66)
Browse files Browse the repository at this point in the history
* fix: union properties can be optional & nullable

* fix: handle null value in union types
  • Loading branch information
tvillaren committed Dec 10, 2021
1 parent e48c5fe commit 2ba1838
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 1 deletion.
39 changes: 39 additions & 0 deletions src/core/generateZodSchema.test.ts
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
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

0 comments on commit 2ba1838

Please sign in to comment.