Skip to main content

Lesson 2 of 7

Zod - Runtime Validation & Type Derivation

Zod is a TypeScript-first validation library where schemas are both the runtime validator AND the type source. Instead of defining a type AND a validator separately (and keeping them in sync manually), you define a Zod schema once and derive the TypeScript type from it. This is the production standard for API input validation.

14 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Zod - Schema-First Type Derivation

Zod - Schema-First Type Derivation
import { z } from "zod";

// ── Define schema - generates both validator AND TypeScript type ──
const PrioritySchema   = z.enum(["low", "medium", "high", "critical"]);
const TaskStatusSchema = z.enum(["todo", "in-progress", "done", "archived"]);

const CreateTaskSchema = z.object({
  title:       z.string().min(1, "Title cannot be empty").max(200),
  priority:    PrioritySchema.default("medium"),
  description: z.string().max(5000).optional(),
  dueDate:     z.string().datetime().optional().transform((v) => v ? new Date(v) : undefined),
  tags:        z.array(z.string().min(1)).max(10).default([]),
});

// ── Derive TypeScript type from schema ────────────────────────
type CreateTaskInput = z.infer<typeof CreateTaskSchema>;
// {
//   title: string;
//   priority: "low" | "medium" | "high" | "critical";   (default: "medium")
//   description?: string;
//   dueDate?: Date;           (transformed from string)
//   tags: string[];           (default: [])
// }

// ── Parse (throws on invalid) ─────────────────────────────────
const rawInput = { title: "Launch feature", priority: "high" };
const validated = CreateTaskSchema.parse(rawInput);
// validated is CreateTaskInput - fully typed AND runtime-checked

// ── safeParse (returns Result - no throw) ─────────────────────
const result = CreateTaskSchema.safeParse(rawInput);
if (result.success) {
  console.log(result.data.title);      // CreateTaskInput
} else {
  console.error(result.error.flatten().fieldErrors);
  // { title: ["Title cannot be empty"], priority: [...] }
}

// ── Full API response schema ──────────────────────────────────
const TaskResponseSchema = z.object({
  id:          z.number(),
  title:       z.string(),
  description: z.string().nullable(),
  status:      TaskStatusSchema,
  priority:    PrioritySchema,
  createdAt:   z.string().datetime().transform((v) => new Date(v)),
  updatedAt:   z.string().datetime().transform((v) => new Date(v)),
  tags:        z.array(z.string()),
});

type TaskResponse = z.infer<typeof TaskResponseSchema>;

// ── Schema composition - extending / merging ──────────────────
const UpdateTaskSchema = CreateTaskSchema.partial().extend({
  status: TaskStatusSchema.optional(),
});
// All CreateTaskSchema fields become optional, plus adds optional status

// ── Express middleware - validate request body ─────────────────
function validateBody<T>(schema: z.ZodSchema<T>) {
  return (req: Request, res: Response, next: NextFunction): void => {
    const result = schema.safeParse(req.body);
    if (!result.success) {
      res.status(400).json({
        error:  "Validation failed",
        fields: result.error.flatten().fieldErrors,
      });
      return;
    }
    req.body = result.data;   // replace raw body with validated + transformed data
    next();
  };
}

// Usage:
router.post("/tasks", authMiddleware, validateBody(CreateTaskSchema), controller.create);

Common Mistakes

  • Defining types separately from Zod schemas - this creates a synchronisation problem. Define the Zod schema first, then `type T = z.infer<typeof Schema>`. The type is always in sync.
  • Using `.parse()` without try/catch - `parse()` throws a `ZodError`. Either use `safeParse()` for explicit handling, or catch `ZodError` specifically in an error handler middleware.
  • Not using `.transform()` for type coercion - Zod's transforms (`.datetime().transform(v => new Date(v))`) run at parse time and the output type reflects the transformation. Without transform, ISO strings stay as strings.

Tip

Tip

Practice Zod Runtime Validation Type Derivation in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and concepts for Zod - Runtime Validation & Type Derivation

Practice Task

Note

Practice Task - (1) Write a working example of Zod Runtime Validation Type Derivation from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Zod Runtime Validation Type Derivation is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready typescript code.

Key Takeaways

  • Zod is a TypeScript-first validation library where schemas are both the runtime validator AND the type source.
  • Defining types separately from Zod schemas - this creates a synchronisation problem. Define the Zod schema first, then `type T = z.infer<typeof Schema>`. The type is always in sync.
  • Using `.parse()` without try/catch - `parse()` throws a `ZodError`. Either use `safeParse()` for explicit handling, or catch `ZodError` specifically in an error handler middleware.
  • Not using `.transform()` for type coercion - Zod's transforms (`.datetime().transform(v => new Date(v))`) run at parse time and the output type reflects the transformation. Without transform, ISO strings stay as strings.

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/7 done