Course contentsShow
← JavaScript
Lesson 2634 of 2,72353. Type Safety Without TypeScriptFree lesson

Defining Basic Schemas

Create schemas for primitives like strings, numbers, and booleans using Zod's fluent API.

Defining Basic Schemas

What you'll learn: How to create Zod schemas for primitive types like strings, numbers, and booleans using a simple, chainable syntax.

The Core Idea

Now that you have Zod installed, it's time to create your first schemas—blueprints that describe what valid data looks like. Think of a schema as a template or mold: you define the shape once, then validate actual data against it at runtime.

Zod provides a fluent API where you call methods on the z object to define types. Each primitive has its own factory method that returns a schema object.

Creating Primitive Schemas

For the three most common primitives, Zod gives you straightforward constructors:

import { z } from 'zod';

const stringSchema = z.string();
const numberSchema = z.number();
const booleanSchema = z.boolean();

Each of these is now a reusable schema. You haven't validated anything yet—you've simply declared "this is what a valid string/number/boolean looks like."

Think of Schemas as Validators

An analogy: if JavaScript types are like labels on boxes (they describe what should be inside), Zod schemas are like inspectors that actually open the box and verify the contents match the label. They work at runtime, catching type mismatches that JavaScript itself wouldn't catch.

You can store these schemas in variables, export them from modules, or inline them wherever validation happens.

Key Takeaway:
Zod's z.string(), z.number(), and z.boolean() create reusable schema objects that describe primitive types—the foundation for runtime type validation.