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

Parenthesized or null #198

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
23 changes: 22 additions & 1 deletion src/core/generateZodSchema.test.ts
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,7 @@ function buildZodPrimitive({
return buildZodPrimitive({
z,
typeNode: typeNode.type,
isNullable,
isOptional,
jsDocTags,
customJSDocFormatTypes,
Expand Down Expand Up @@ -744,7 +745,7 @@ function buildZodPrimitive({
customJSDocFormatTypes,
});

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

return withZodProperties(zodCall, zodProperties);
}

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