0Pricing
TypeScript Academy · Lesson

parse vs safeParse

Handle validation success and failure gracefully.

Two Ways to Validate

Zod gives you two validation methods: parse, which throws on invalid data, and safeParse, which returns a result object instead.

import { z } from "zod";
const schema = z.string();
// schema.parse(x) throws on failure
// schema.safeParse(x) returns { success, ... }

parse Throws on Invalid Data

parse returns the validated value on success and throws a ZodError on failure, ideal when invalid data is truly exceptional.

import { z } from "zod";
const schema = z.number();
const ok = schema.parse(42); // 42
// schema.parse("nope"); // throws ZodError

All lessons in this course

  1. Zod Schema Basics
  2. Inferring Types from Schemas
  3. parse vs safeParse
  4. Composing and Refining Schemas
← Back to TypeScript Academy