(Translated by https://www.hiragana.jp/)
GitHub - kentcdodds/zod: TypeScript-first schema validation with static type inference
Skip to content
/ zod Public
forked from colinhacks/zod

TypeScript-first schema validation with static type inference

License

Notifications You must be signed in to change notification settings

kentcdodds/zod

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Zod logo

Zod

https://zod.dev
TypeScript-first schema validation with static type inference


Zod CI status Created by Colin McDonnell License npm stars discord server

Documentation   •   Discord   •   npm   •   deno   •   Issues   •   @colinhacks   •   tRPC


These docs have been translated into Chinese.

Table of contents

Introduction

Zod is a TypeScript-first schema declaration and validation library. I'm using the term "schema" to broadly refer to any data type, from a simple string to a complex nested object.

Zod is designed to be as developer-friendly as possible. The goal is to eliminate duplicative type declarations. With Zod, you declare a validator once and Zod will automatically infer the static TypeScript type. It's easy to compose simpler types into complex data structures.

Some other great aspects:

  • Zero dependencies
  • Works in Node.js and all modern browsers
  • Tiny: 8kb minified + zipped
  • Immutable: methods (e.g. .optional()) return a new instance
  • Concise, chainable interface
  • Functional approach: parse, don't validate
  • Works with plain JavaScript too! You don't need to use TypeScript.

Sponsors

Sponsorship at any level is appreciated and encouraged. For individual developers, consider the Cup of Coffee tier. If you built a paid product using Zod, consider one of the podium tiers.

Gold

Astro
Astro
astro.build

Astro is a new kind of static
site builder for the modern web.
Powerful developer experience meets
lightweight output.


Glow Wallet
glow.app

Your new favorite
Solana wallet.

Deletype logo
Deletype
deletype.com
Proxy logo
Proxy
proxy.com
Trigger.dev logo
Trigger.dev
trigger.dev

Effortless automation for developers.

Transloadit logo
Transloadit
transloadit.com

Simple file processing for developers.

Infisical logo
Infisical
infisical.com

Open-source platform for secret
management: sync secrets across your
team/infrastructure and prevent secret leaks.

Silver

Numeric logo
Numeric
numeric.io
Snaplet logo
Snaplet
snaplet.dev
Marcato Partners
Marcato Partners
marcatopartners.com

Interval
interval.com

Seasoned Software
seasoned.cc
Bamboo Creative logo
Bamboo Creative
bamboocreative.nz

Bronze


Brandon Bayer
@flybayer, creator of Blitz.js

Jiří Brabec
@brabeji

Alex Johansson
@alexdotjs
Fungible Systems logo
Fungible Systems
fungible.systems

Adaptable
adaptable.io
Avana Wallet logo
Avana Wallet
avanawallet.com
Solana non-custodial wallet
Learn with Jason logo
Jason Lengstorf
learnwithjason.dev
Global Illumination
Global Illumination, Inc.
ill.inc
MasterBorn logo
MasterBorn
masterborn.com

Ecosystem

There are a growing number of tools that are built atop or support Zod natively! If you've built a tool or library on top of Zod, tell me about it on Twitter or start a Discussion. I'll add it below and tweet it out.

Resources

API libraries

  • tRPC: Build end-to-end typesafe APIs without GraphQL.
  • @anatine/zod-nestjs: Helper methods for using Zod in a NestJS project.
  • zod-endpoints: Contract-first strictly typed endpoints with Zod. OpenAPI compatible.
  • domain-functions: Decouple your business logic from your framework using composable functions. With first-class type inference from end to end powered by Zod schemas.
  • @zodios/core: A typescript API client with runtime and compile time validation backed by axios and zod.
  • express-zod-api: Build Express-based APIs with I/O schema validation and custom middlewares.
  • tapiduck: End-to-end typesafe JSON APIs with Zod and Express; a bit like tRPC, but simpler.
  • koa-zod-router: Create typesafe routes in Koa with I/O validation using Zod.

Form integrations

  • react-hook-form: A first-party Zod resolver for React Hook Form.
  • zod-validation-error: Generate user-friendly error messages from ZodErrors.
  • zod-formik-adapter: A community-maintained Formik adapter for Zod.
  • react-zorm: Standalone <form> generation and validation for React using Zod.
  • zodix: Zod utilities for FormData and URLSearchParams in Remix loaders and actions.
  • remix-params-helper: Simplify integration of Zod with standard URLSearchParams and FormData for Remix apps.
  • formik-validator-zod: Formik-compliant validator library that simplifies using Zod with Formik.
  • zod-i18n-map: Useful for translating Zod error messages.
  • @modular-forms/solid: Modular form library for SolidJS that supports Zod for validation.
  • houseform: A React form library that uses Zod for validation.
  • sveltekit-superforms: Supercharged form library for SvelteKit with Zod validation.
  • mobx-zod-form: Data-first form builder based on MobX & Zod

Zod to X

X to Zod

Mocking

  • @anatine/zod-mock: Generate mock data from a Zod schema. Powered by faker.js.
  • zod-mocking: Generate mock data from your Zod schemas.
  • zod-fixture: Use your zod schemas to automate the generation of non-relevant test fixtures in a deterministic way.
  • zocker: Generate plausible mock-data from your schemas.
  • zodock Generate mock data based on Zod schemas.

Powered by Zod

  • freerstore: Firestore cost optimizer.
  • slonik: Node.js Postgres client with strong Zod integration.
  • soly: Create CLI applications with zod.
  • zod-xlsx: A xlsx based resource validator using Zod schemas.
  • znv: Type-safe environment parsing and validation for Node.js with Zod schemas.

Utilities for Zod

  • zod_utilz: Framework agnostic utilities for Zod.

Installation

Requirements

  • TypeScript 4.5+!

  • You must enable strict mode in your tsconfig.json. This is a best practice for all TypeScript projects.

    // tsconfig.json
    {
      // ...
      "compilerOptions": {
        // ...
        "strict": true
      }
    }

From npm (Node/Bun)

npm install zod       # npm
yarn add zod          # yarn
bun add zod           # bun
pnpm add zod          # pnpm

Zod also publishes a canary version on every commit. To install the canary:

npm install zod@canary       # npm
yarn add zod@canary          # yarn
bun add zod@canary           # bun
pnpm add zod@canary          # pnpm

From deno.land/x (Deno)

Unlike Node, Deno relies on direct URL imports instead of a package manager like NPM. Zod is available on deno.land/x. The latest version can be imported like so:

import { z } from "https://deno.land/x/zod/mod.ts";

You can also specify a particular version:

import { z } from "https://deno.land/x/zod@v3.16.1/mod.ts";

The rest of this README assumes you are using npm and importing directly from the "zod" package.

Basic usage

Creating a simple string schema

import { z } from "zod";

// creating a schema for strings
const mySchema = z.string();

// parsing
mySchema.parse("tuna"); // => "tuna"
mySchema.parse(12); // => throws ZodError

// "safe" parsing (doesn't throw error if validation fails)
mySchema.safeParse("tuna"); // => { success: true; data: "tuna" }
mySchema.safeParse(12); // => { success: false; error: ZodError }

Creating an object schema

import { z } from "zod";

const User = z.object({
  username: z.string(),
});

User.parse({ username: "Ludwig" });

// extract the inferred type
type User = z.infer<typeof User>;
// { username: string }

Primitives

import { z } from "zod";

// primitive values
z.string();
z.number();
z.bigint();
z.boolean();
z.date();
z.symbol();

// empty types
z.undefined();
z.null();
z.void(); // accepts undefined

// catch-all types
// allows any value
z.any();
z.unknown();

// never type
// allows no values
z.never();

Coercion for primitives

Zod now provides a more convenient way to coerce primitive values.

const schema = z.coerce.string();
schema.parse("tuna"); // => "tuna"
schema.parse(12); // => "12"
schema.parse(true); // => "true"

During the parsing step, the input is passed through the String() function, which is a JavaScript built-in for coercing data into strings. Note that the returned schema is a ZodString instance so you can use all string methods.

z.coerce.string().email().min(5);

All primitive types support coercion.

z.coerce.string(); // String(input)
z.coerce.number(); // Number(input)
z.coerce.boolean(); // Boolean(input)
z.coerce.bigint(); // BigInt(input)
z.coerce.date(); // new Date(input)

Boolean coercion

Zod's boolean coercion is very simple! It passes the value into the Boolean(value) function, that's it. Any truthy value will resolve to true, any falsy value will resolve to false.

z.coerce.boolean().parse("tuna"); // => true
z.coerce.boolean().parse("true"); // => true
z.coerce.boolean().parse("false"); // => true
z.coerce.boolean().parse(1); // => true
z.coerce.boolean().parse([]); // => true

z.coerce.boolean().parse(0); // => false
z.coerce.boolean().parse(undefined); // => false
z.coerce.boolean().parse(null); // => false

Literals

Literal schemas represent a literal type, like "hello world" or 5.

const tuna = z.literal("tuna");
const twelve = z.literal(12);
const twobig = z.literal(2n); // bigint literal
const tru = z.literal(true);

const terrificSymbol = Symbol("terrific");
const terrific = z.