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

Omit the undefined type when the object property is marked as optional #83

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
9 changes: 7 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,12 +134,17 @@ const zodToTsNode = (
const properties = Object.entries(zod._def.shape())

const members: ts.TypeElement[] = properties.map(([key, value]) => {
const nextZodNode = value as ZodTypeAny
const type = zodToTsNode(nextZodNode, ...otherArguments)
let nextZodNode = value as ZodTypeAny

const { typeName: nextZodNodeTypeName } = nextZodNode._def
const isOptional = nextZodNodeTypeName === 'ZodOptional' || nextZodNode.isOptional()

if (nextZodNodeTypeName === 'ZodOptional') {
nextZodNode = nextZodNode.unwrap()
}

const type = zodToTsNode(nextZodNode, ...otherArguments)

const propertySignature = f.createPropertySignature(
undefined,
getIdentifierOrStringLiteral(key),
Expand Down
6 changes: 3 additions & 3 deletions test/modifiers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,18 +31,18 @@ describe('z.optional()', () => {

expect(printNodeTest(node)).toMatchInlineSnapshot(`
"{
optional?: string | undefined;
optional?: string;
required: string;
transform?: number | undefined;
or?: (number | undefined) | string;
tuple?: [
string | undefined,
number,
{
optional?: string | undefined;
optional?: string;
required: string;
}
] | undefined;
];
}"
`)
})
Expand Down