Course contentsShow
← TypeScript
Lesson 1288 of 1,79630. Type-Safe APIsFree lesson

Primitive Schemas in Zod

Define string, number, boolean, date, and other primitive types with z.string(), z.number(), etc.

Primitive Schemas in Zod

What you'll learn: How to define type-safe schemas for basic primitive types using Zod's built-in schema creators.

Why Primitive Schemas Matter

Now that you understand Zod creates a single source of truth for both runtime validation and static types, you need to actually build schemas. Every complex schema starts with primitives—the fundamental building blocks like strings, numbers, and booleans.

Think of primitive schemas as the atoms of your validation logic. Just as you build molecules from atoms, you'll build complex API response types from these basic primitives.

Core Primitive Schema Functions

Zod provides dedicated functions for each JavaScript primitive type:

  • z.string() — validates string values
  • z.number() — validates numeric values
  • z.boolean() — validates true/false values
  • z.date() — validates Date objects
  • z.bigint() — validates BigInt values
  • z.symbol() — validates Symbol values
  • z.null() — validates null specifically
  • z.undefined() — validates undefined specifically

Each function creates a schema object that both validates at runtime and provides TypeScript type information.

How They Work Together

When you call z.string(), you get back a Zod schema that knows how to check if a value is a string. Later, you'll parse data through this schema. If validation succeeds, TypeScript automatically knows the validated data is a string—no type assertions needed.

The beauty is symmetry: one declaration (z.string()) gives you runtime safety (actual validation) and compile-time safety (TypeScript types inferred automatically).

Key Takeaway: Zod's primitive schemas (z.string(), z.number(), z.boolean(), z.date(), etc.) are the foundational building blocks for type-safe validation—each function creates a schema that both validates runtime data and infers the correct TypeScript type.