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

Using undefined() incorrectly marks keys as optional #2464

Open
AndrewRayCode opened this issue May 27, 2023 · 4 comments
Open

Using undefined() incorrectly marks keys as optional #2464

AndrewRayCode opened this issue May 27, 2023 · 4 comments

Comments

@AndrewRayCode
Copy link

AndrewRayCode commented May 27, 2023

From this Stackoverflow question (I'm hitting the same thing):

This code:

const schema = z.object({
  x: z.string().or(z.undefined()),
});
type Schema = z.infer<typeof schema>;

Produces a schema with an optional key:

type Schema = {
    x?: string | undefined;
}

Same with:

z.undefined().or(z.string())

Same with any variation of union (which seems to be how .or() resolves under the hood anyway)

x: z.union([z.string(), z.number(), z.undefined()])
@kemilbeltre
Copy link

@AndrewRayCode what is expected to resolve this issue?

@AndrewRayCode
Copy link
Author

AndrewRayCode commented Jun 18, 2023

@kemilbeltre There is a hack you can use in the linked Stackoverflow question. I couldn't use that for my app so I sadly had to refactor my core domain types to make the key optional. Zod doesn't seem to handle undefined types correctly which is ironic considering the author says Zod is better at type inference than Yup:

But it's very uncool for the inferred type to not actually reflect the actual type of the validator it came from.

There seems to be something fundamentally wrong with Zod, because this doesn't work either:

const stringOrUndefined = z.custom<string | undefined>(
  (v) => typeof v === 'string' || v === undefined
);
const mySchema = z.object({ field: stringOrUndefined });
type Schema = z.infer<typeof mySchema>;

Results in

type Schema = {
    field?: string | undefined;
}

@stale
Copy link

stale bot commented Sep 17, 2023

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

@stale stale bot added the stale No activity in last 60 days label Sep 17, 2023
@AndrewRayCode
Copy link
Author

Doesn't seem stale given the reports (stackoverflow, this report, and #2598)

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

No branches or pull requests

2 participants