Skip to content

Commit

Permalink
fix: Fix optional function parameter (#48)
Browse files Browse the repository at this point in the history
Closed #47
  • Loading branch information
fabien0102 committed Oct 7, 2021
1 parent 1e13bbb commit bf0d527
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 2 deletions.
5 changes: 5 additions & 0 deletions example/heros.ts
Expand Up @@ -84,3 +84,8 @@ export interface Exported {
a: NonExported;
b: string;
}

export type GetSupermanSkill = (
skillName: string,
withKryptonite?: boolean
) => string;
5 changes: 5 additions & 0 deletions example/heros.zod.ts
Expand Up @@ -64,3 +64,8 @@ export const exportedSchema = z.object({
a: nonExportedSchema,
b: z.string(),
});

export const getSupermanSkillSchema = z
.function()
.args(z.string(), z.boolean().optional())
.returns(z.string());
11 changes: 11 additions & 0 deletions src/core/generateZodSchema.test.ts
Expand Up @@ -221,6 +221,17 @@ describe("generateZodSchema", () => {
);
});

it("should generate a function with optional parameter", () => {
const source = `export type GetSupermanSkill = (
key: string,
params?: Record<string, string | number>
) => string`;

expect(generate(source)).toMatchInlineSnapshot(
`"export const getSupermanSkillSchema = z.function().args(z.string(), z.record(z.union([z.string(), z.number()])).optional()).returns(z.string());"`
);
});

it("should generate a function schema (with `any` fallback on param)", () => {
const source = `export type KillSuperman = (withKryptonite: boolean, method) => Promise<boolean>;`;
expect(generate(source)).toMatchInlineSnapshot(
Expand Down
4 changes: 2 additions & 2 deletions src/core/generateZodSchema.ts
Expand Up @@ -287,7 +287,7 @@ function buildZodPrimitive({
buildZodPrimitive({
z,
typeNode: typeNode.typeArguments[1],
isOptional,
isOptional: false,
jsDocTags,
sourceFile,
isPartial: false,
Expand Down Expand Up @@ -572,7 +572,7 @@ function buildZodPrimitive({
sourceFile,
dependencies,
getDependencyName,
isOptional: false,
isOptional: Boolean(p.questionToken),
})
),
},
Expand Down

0 comments on commit bf0d527

Please sign in to comment.