Skip to content

Commit

Permalink
fix: Support parenthesized or null (#198)
Browse files Browse the repository at this point in the history
  • Loading branch information
williamputraintan committed Jan 16, 2024
1 parent 26ccb38 commit 6cff78c
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
23 changes: 22 additions & 1 deletion src/core/generateZodSchema.test.ts
Expand Up @@ -605,13 +605,34 @@ describe("generateZodSchema", () => {
);
});

it("should deal with parenthesized type", () => {
it("should deal with parenthesized schema type", () => {
const source = `export type SecretVillain = (NormalGuy | Villain);`;
expect(generate(source)).toMatchInlineSnapshot(
`"export const secretVillainSchema = z.union([normalGuySchema, villainSchema]);"`
);
});

it("should deal with parenthesized type or null", () => {
const source = `export type SecretVillain = (NormalGuy | Villain) | null;`;
expect(generate(source)).toMatchInlineSnapshot(
`"export const secretVillainSchema = z.union([normalGuySchema, villainSchema]).nullable();"`
);
});

it("should deal with literal parenthesized type or null", () => {
const source = `export type Example = ("A" | "B") | null;`;
expect(generate(source)).toMatchInlineSnapshot(
`"export const exampleSchema = z.union([z.literal("A"), z.literal("B")]).nullable();"`
);
});

it("should deal with joined schema parenthesized type or null", () => {
const source = `export type person = (NormalGuy & BadGuy & randomGuy) | null;`;
expect(generate(source)).toMatchInlineSnapshot(
`"export const personSchema = normalGuySchema.and(badGuySchema).and(randomGuySchema).nullable();"`
);
});

it("should deal with index signature", () => {
const source = `export type Movies = {[title: string]: Movie};`;
expect(generate(source)).toMatchInlineSnapshot(
Expand Down
5 changes: 4 additions & 1 deletion src/core/generateZodSchema.ts
Expand Up @@ -269,6 +269,7 @@ function buildZodPrimitive({
return buildZodPrimitive({
z,
typeNode: typeNode.type,
isNullable,
isOptional,
jsDocTags,
customJSDocFormatTypes,
Expand Down Expand Up @@ -745,7 +746,7 @@ function buildZodPrimitive({
customJSDocFormatTypes,
});

return rest.reduce(
const zodCall = rest.reduce(
(intersectionSchema, node) =>
f.createCallExpression(
f.createPropertyAccessExpression(
Expand All @@ -769,6 +770,8 @@ function buildZodPrimitive({
),
basePrimitive
);

return withZodProperties(zodCall, zodProperties);
}

if (ts.isLiteralTypeNode(typeNode)) {
Expand Down

0 comments on commit 6cff78c

Please sign in to comment.