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

feat: add safeParseOptional to return an optional result #3242

Closed

Conversation

jonlambert
Copy link

@jonlambert jonlambert commented Feb 15, 2024

safeParse is a very useful function to use when validating, however there are often circumstances in which a user might not need access to an error, and would like to use optional chaining on the result. Unfortunately, to do this one would need to narrow the result object based on the success flag.

For example, the following is impossible:

const schema = z.object({ name: z.string() });

const getName = (data: unknown) => schema.safeParse(data).data?.name;
                                                        // ^ Property 'data' does not exist on type 'SafeParseReturnType<{ name: string; }, { name: string; }>'.

Instead one would need to take a more verbose approach:

const schema = z.object({ name: z.string() });

const getName = (data: unknown) => {
  const result = schema.safeParse(data);
  return result.success ? result.data.name : undefined;
};

Or, cast to any directly (as is done in the Zod tests).

I tend to use a tiny util in most projects that runs the above checks. I thought it might be worthwhile opening a very basic PR to add this to Zod in case others might find this useful!

If this approach is agreed, I would be happy to expand documentation to cover this.

(ps. I did have a dig in past PRs to see if anyone has covered this already but couldn't find anything. Apologies if this is duplicated work!)

Copy link

netlify bot commented Feb 15, 2024

Deploy Preview for guileless-rolypoly-866f8a ready!

Built without sensitive environment variables

Name Link
🔨 Latest commit 3ec81ca
🔍 Latest deploy log https://app.netlify.com/sites/guileless-rolypoly-866f8a/deploys/65ce1d15b7a8a5000885f3c7
😎 Deploy Preview https://deploy-preview-3242--guileless-rolypoly-866f8a.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

@colinhacks
Copy link
Owner

colinhacks commented Apr 19, 2024

With #3295 merged this is now possible in zod@beta (without the addition of a new method)

const schema = z.object({ name: z.string() });

const getName = (data: unknown) => schema.safeParse(data).data?.name;

Landing in Zod 3.23 in the next couple days

@colinhacks colinhacks closed this Apr 19, 2024
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 this pull request may close these issues.

2 participants