DEV Community

Arhan Khan
Arhan Khan

Posted on

Zod for Beginners: Stop Guessing What Your Data Looks Like

Zod is a TypeScript-first validation library, and it solves a problem every developer hits sooner or later: data from the outside world — an API, a form, a file — is never the shape you hope it is. Zod lets you describe the shape once, validate any data against it, and get a TypeScript type for free. One definition, two guarantees.

The idea is simple. You write a schema that says what your data should look like. Zod checks incoming data against it, tells you exactly what is wrong if it fails, and gives you back data that TypeScript knows is correct. No more as casts, no more runtime surprises, no more writing the same shape twice.

import { z } from "zod";

const UserSchema = z.object({
  name: z.string().min(1, "Name is required"),
  email: z.string().email("Must be a valid email"),
  age: z.number().int().min(18, "Must be 18 or older"),
  role: z.enum(["admin", "user", "guest"]).default("user"),
});

// TypeScript type, generated automatically
type User = z.infer<typeof UserSchema>;

// Validate unknown data
const result = UserSchema.safeParse(someDataFromApi);
if (result.success) {
  console.log(result.data.name); // TypeScript knows this is a string
} else {
  console.log(result.error.issues); // Exactly what went wrong
}
Enter fullscreen mode Exit fullscreen mode

Getting started is simple. Run npm install zod, write one schema for the messiest data in your project, and validate it. The docs are excellent, and the API is small enough to learn in an evening — most developers use just z.object, z.string, z.number, z.array, and z.enum for 90% of their work.

Zod is for TypeScript developers who consume APIs, beginners who want to stop writing defensive if checks everywhere, and teams building forms, backends, or anything where bad input causes bugs. It pairs perfectly with React Hook Form, tRPC, and Express.

The limits are honest. Zod adds a dependency and a small runtime cost, and its error messages need customizing for user-facing forms. It validates at runtime, so it cannot catch mistakes in code that never runs — TypeScript still does that job.

Start today with one thing: take one API response in your project and write a Zod schema for it. Replace your manual checks with safeParse. In a week every boundary in your app will be validated — and the "undefined is not a function" bugs will start disappearing.

Top comments (0)