Skip to content

cu-fs1/zod

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 

Repository files navigation

Zod: TypeScript-First Schema Validation

Zod is a TypeScript-first schema declaration and validation library. It allows you to define a schema once and automatically infer the static TypeScript type, ensuring that your data is always in the expected format.


1. Why Zod?

  • Zero dependencies: Tiny footprint.
  • Type safety: Automatically generates TypeScript types from your schemas.
  • Developer experience: Concise, readable, and chainable API.
  • Works everywhere: Node.js, Browsers, and Deno.
  • Immutable: Every method returns a new schema instance.

2. Getting Started

Installation

pnpm i zod

Basic Usage

Define a schema, then use it to validate data.

import { z } from "zod";

// 1. Define a schema
const UserSchema = z.object({
  username: z.string().min(3),
  age: z.number().positive(),
  email: z.string().email(),
});

// 2. Validate data
const result = UserSchema.parse({
  username: "johndoe",
  age: 25,
  email: "john@example.com",
});

console.log(result); // { username: "johndoe", age: 25, email: "john@example.com" }

3. Parsing and Validation

.parse(data)

Validates the data and returns it. If invalid, it throws a ZodError.

try {
  UserSchema.parse({ username: "jo" }); // Throws error (too short)
} catch (e) {
  console.log(e.issues);
}

.safeParse(data)

Returns an object with either the data or an error. Use this to avoid try/catch blocks.

const result = UserSchema.safeParse({ username: "jo" });

if (result.success) {
  console.log(result.data);
} else {
  console.log(result.error.format()); // User-friendly error object
}

4. Primitive Schemas

Zod supports all basic JavaScript types.

z.string();
z.number();
z.bigint();
z.boolean();
z.date();
z.null();
z.undefined();
z.any();     // Allows anything
z.unknown(); // Safer "any"

Coercion

You can force Zod to convert (coerce) input data to the desired type.

const schema = z.coerce.number();
schema.parse("123"); // Returns 123 (number)
schema.parse(true);  // Returns 1 (number)

5. Object Schemas

Objects are the bread and butter of Zod.

const User = z.object({
  name: z.string(),
  role: z.enum(["admin", "user"]),
});

// Extend a schema
const Mod = User.extend({
  permissions: z.array(z.string()),
});

// Strip unknown keys (Default Behavior)
User.parse({ name: "Alice", role: "user", extra: "ignore me" }); // { name: "Alice", role: "user" }

// Allow unknown keys
const Passthrough = User.passthrough();

// Throw if unknown keys are present
const Strict = User.strict();

6. Arrays & Sets

const StringArray = z.array(z.string());
const NumberSet = z.set(z.number());

StringArray.parse(["a", "b", "c"]);

7. Type Inference

This is Zod's superpower. You don't need to write the interface/type twice!

const UserSchema = z.object({
  name: z.string(),
  age: z.number(),
});

// Automatically extract the TypeScript type
type User = z.infer<typeof UserSchema>;

// Now you can use 'User' as a normal TypeScript type
const myUser: User = {
  name: "Bob",
  age: 30,
};

8. Common Validations

Strings

z.string().min(5).max(10);
z.string().email();
z.string().url();
z.string().uuid();
z.string().regex(/^[a-zA-Z]+$/);
z.string().includes("hello");
z.string().startsWith("a").endsWith("z");

Numbers

z.number().gt(5);      // Greater than
z.number().gte(5);     // Greater than or equal to
z.number().lt(10);     // Less than
z.number().lte(10);    // Less than or equal to
z.number().int();      // Must be an integer
z.number().positive(); // > 0

9. Optionals and Nullables

Everything in Zod is required by default.

z.string().optional(); // string | undefined
z.string().nullable(); // string | null
z.string().nullish();  // string | null | undefined

10. Refinements & Transformations

.refine()

Add custom validation logic.

const PasswordSchema = z.string().refine((val) => val.length > 8, {
  message: "Password must be at least 8 characters long",
});

.transform()

Modify the data during validation.

const TrimSchema = z.string().transform((val) => val.trim());
TrimSchema.parse("  hello  "); // "hello"

const StringToNumber = z.string().transform((val) => val.length);
StringToNumber.parse("abc"); // 3

11. Error Handling

When parsing fails, Zod provides a ZodError object.

const result = z.string().safeParse(123);
if (!result.success) {
  console.log(result.error.issues);
  /*
  [
    {
      "code": "invalid_type",
      "expected": "string",
      "received": "number",
      "path": [],
      "message": "Expected string, received number"
    }
  ]
  */
}

Summary Checklist for Students

  1. Define: const mySchema = z...
  2. Infer: type MyType = z.infer<typeof mySchema>
  3. Validate: mySchema.parse(data) or mySchema.safeParse(data)
  4. Handle: Manage errors if validation fails.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors