Skip to content

Instantly share code, notes, and snippets.

@gustavomorinaga
Created July 21, 2023 17:59
Show Gist options
  • Select an option

  • Save gustavomorinaga/0b0c590d8b3c7c9e6f09692425dfef24 to your computer and use it in GitHub Desktop.

Select an option

Save gustavomorinaga/0b0c590d8b3c7c9e6f09692425dfef24 to your computer and use it in GitHub Desktop.
Best way to parse and validate data with Zod in any context.
import { AnyZodObject, ZodError, z } from 'zod';
import { fromZodError } from 'zod-validation-error';
export async function zParse<T extends AnyZodObject>(
schema: T,
data: any
): Promise<z.infer<T>> {
try {
return await schema.parseAsync(data);
} catch (error) {
throw fromZodError(error as ZodError);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment