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

Optional & nullable not output together on optional union type property with null value #65

Closed
tvillaren opened this issue Dec 8, 2021 · 2 comments · Fixed by #66
Closed

Comments

@tvillaren
Copy link
Collaborator

tvillaren commented Dec 8, 2021

Bug description

When an optional property references a union type with null, the result is not using the optional() modifier

Input

export interface A {
  a?: number | null;
}

Expected output

export const aSchema = z.object({
  a: z.number().optional().nullable()
});

Actual output

export const aSchema = z.object({
  a: z.number().nullable()
});

Potential fix

Did some fiddling on a fork, and found that the isOptional flag was not passed down in case of an union type traversal.

Versions

  • Typescript: v4.5.2
  • Zod: v1.7.0
@tvillaren
Copy link
Collaborator Author

tvillaren commented Dec 8, 2021

Actually, my PR doesn't fix all cases, only the "simple" one.

Union with multiple primitive types and null fails as well:

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()
      });"
    `);
  });

I proposed a fix in my PR as well.

@fabien0102
Copy link
Owner

Part of 1.8.0 release 😀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants