### Install Zod Source: https://zod.dev/packages/mini Install Zod version 4.0.0 or higher to use Zod Mini. ```bash npm install zod@^4.0.0 ``` -------------------------------- ### Zod Mini Boolean Schema Example Source: https://zod.dev/v4 A minimal example demonstrating a boolean schema in Zod Mini and its parse method. ```typescript import * as z from "zod/mini"; const schema = z.boolean(); schema.parse(false); ``` -------------------------------- ### Install Zod via npm Source: https://zod.dev/?id=introduction Install the Zod library using npm. This command adds Zod to your project's dependencies. ```bash npm install zod ``` -------------------------------- ### Running Benchmarks in Zod Repo Source: https://zod.dev/v4?id=14x-faster-string-parsing Clone the Zod repository, switch to the v4 branch, install dependencies, and run benchmarks. ```bash $ git clone git@github.com:colinhacks/zod.git $ cd zod $ git switch v4 $ pnpm install ``` ```bash $ pnpm bench ``` -------------------------------- ### Install Zod using npm Source: https://zod.dev Install the Zod library using npm. Ensure you are using TypeScript v5.5 or later and have 'strict' mode enabled in your tsconfig.json. ```bash npm install zod ``` -------------------------------- ### Template Literal Examples Source: https://zod.dev/api?id=when Demonstrates various ways to use `z.templateLiteral` with different combinations of string literals and compatible schemas. ```typescript z.templateLiteral([ "hi there" ]); // `hi there` ``` ```typescript z.templateLiteral([ "email: ", z.string() ]); // `email: ${string}` ``` ```typescript z.templateLiteral([ "high", z.literal(5) ]); // `high5` ``` ```typescript z.templateLiteral([ z.nullable(z.literal("grassy")) ]); // `grassy` | `null` ``` ```typescript z.templateLiteral([ z.number(), z.enum(["px", "em", "rem"]) ]); // `${number}px` | `${number}em` | `${number}rem` ``` -------------------------------- ### Add and Get Schemas from a Registry Source: https://zod.dev/v4?id=65x-faster-object-parsing Associate schemas with metadata using `.add()` and retrieve them using `.get()`. ```typescript const emailSchema = z.string().email(); myRegistry.add(emailSchema, { title: "Email address", description: "..." }); myRegistry.get(emailSchema); // => { title: "Email address", ... } ``` -------------------------------- ### Importing Zod Mini Source: https://zod.dev/packages/mini?id=register To use Zod Mini, install zod version 4.0.0 or higher and import it using the 'zod/mini' path. ```bash npm install zod@^4.0.0 ``` ```typescript import * as z from "zod/mini"; ``` -------------------------------- ### Example Pretty-Printed Zod Error Output Source: https://zod.dev/v4?id=14x-faster-string-parsing This is an example of the multi-line string output generated by z.prettifyError for a ZodError object. ```text ✖ Unrecognized key: "extraField" ✖ Invalid input: expected string, received number → at username ✖ Invalid input: expected number, received string → at favoriteNumbers[1] ``` -------------------------------- ### Use .describe() for Metadata (Zod 3 Compatibility) Source: https://zod.dev/v4 Illustrates the use of the `.describe()` method for adding schema descriptions, noting that `.meta()` is the preferred modern approach. ```typescript z.string().describe("An email address"); // equivalent to z.string().meta({ description: "An email address" }); ``` -------------------------------- ### Examples of Template Literal Schemas Source: https://zod.dev/api?id=apply Demonstrates various ways to construct template literal schemas, including with only strings, strings and schemas, and different schema types. ```typescript z.templateLiteral([ "hi there" ]); // `hi there` z.templateLiteral([ "email: ", z.string() ]); // `email: ${string}` z.templateLiteral([ "high", z.literal(5) ]); // `high5` z.templateLiteral([ z.nullable(z.literal("grassy")) ]); // `grassy` | `null` z.templateLiteral([ z.number(), z.enum(["px", "em", "rem"]) ]); // `${number}px` | `${number}em` | `${number}rem` ``` -------------------------------- ### Example Usage of Library Supporting Zod and Zod Mini Source: https://zod.dev/library-authors Demonstrates how user code can utilize a library function designed to accept both Zod 4 and Zod Mini schemas by importing from the respective Zod packages. ```typescript // user code import { acceptObjectSchema } from "your-library"; // Zod 4 import * as z from "zod"; acceptObjectSchema(z.object({ name: z.string() })); // Zod 4 Mini import * as zm from "zod/mini"; acceptObjectSchema(zm.object({ name: zm.string() })) ``` -------------------------------- ### Create a Custom Schema Registry Source: https://zod.dev/v4 Demonstrates how to create a custom schema registry with specific metadata types using `z.registry()`. ```typescript import * as z from "zod"; const myRegistry = z.registry<{ title: string; description: string }>(); ``` -------------------------------- ### Zod 3 literal union example Source: https://zod.dev/v4?id=multiple-values-in-zliteral This example shows the Zod 3 approach to matching multiple literal values using `z.union()`, contrasted with the simpler `z.literal()` array syntax in Zod 4. ```typescript const httpCodes = z.union([ z.literal(200), z.literal(201), z.literal(202), z.literal(204), z.literal(206), z.literal(207), z.literal(208), z.literal(226) ]); ``` -------------------------------- ### Pretty-printed Error Output Source: https://zod.dev/v4?id=66x-reduction-in-core-bundle-size Example of the output from `z.prettifyError()`, showing a formatted, human-readable error message. ```text ✖ Unrecognized key: "extraField" ✖ Invalid input: expected string, received number → at username ✖ Invalid input: expected number, received string → at favoriteNumbers[1] ``` -------------------------------- ### Create a Basic Custom Registry Source: https://zod.dev/metadata?id=metadata Initialize a custom Zod registry with a specific metadata type. ```typescript import * as z from "zod"; const myRegistry = z.registry<{ description: string }>(); ``` -------------------------------- ### Prettified Error Output Source: https://zod.dev/error-formatting?id=zflattenerror This shows the string output generated by z.prettifyError() for the example invalid data. ```text ✖ Unrecognized key: "extraKey" ✖ Invalid input: expected string, received number → at username ✖ Invalid input: expected number, received string → at favoriteNumbers[1] ``` -------------------------------- ### Add, Get, and Remove Schemas from a Registry Source: https://zod.dev/metadata?id=metadata Demonstrates the basic operations of adding a schema with metadata, checking for its existence, retrieving it, and removing it from a registry. ```typescript const mySchema = z.string(); myRegistry.add(mySchema, { description: "A cool schema!"}); myRegistry.has(mySchema); // => true myRegistry.get(mySchema); // => { description: "A cool schema!" } myRegistry.remove(mySchema); myRegistry.clear(); // wipe registry ``` -------------------------------- ### Extracting Enum Values Source: https://zod.dev/api?id=enum Use the `.enum` property to get an object with the enum's values. ```APIDOC ### `.enum` To extract the schema's values as an enum-like object: ```typescript const FishEnum = z.enum(["Salmon", "Tuna", "Trout"]); FishEnum.enum; // => { Salmon: "Salmon", Tuna: "Tuna", Trout: "Trout" } ``` ``` -------------------------------- ### Using a Zod Codec for Decoding and Encoding Source: https://zod.dev/codecs?id=jsonschema Shows the runtime behavior of a custom codec, demonstrating how .decode() converts an ISO string to a Date object and .encode() converts a Date object to an ISO string. ```typescript stringToDate.decode("2024-01-15T10:30:00.000Z") // => Date stringToDate.encode(new Date("2024-01-15T10:30:00.000Z")) // => string ``` -------------------------------- ### Template Literal Examples Source: https://zod.dev/api Demonstrates various ways to define template literal schemas with different combinations of string literals and Zod schemas. ```typescript z.templateLiteral([ "hi there" ]); // `hi there` z.templateLiteral([ "email: ", z.string() ]); // `email: ${string}` z.templateLiteral([ "high", z.literal(5) ]); // `high5` z.templateLiteral([ z.nullable(z.literal("grassy")) ]); // `grassy` | `null` z.templateLiteral([ z.number(), z.enum(["px", "em", "rem"]) ]); // `${number}px` | `${number}em` | `${number}rem` ``` -------------------------------- ### Displaying Custom Error Path Source: https://zod.dev/api?id=apply This example shows how the `path` option affects the reported issues after parsing. ```typescript const result = passwordForm.safeParse({ password: "asdf", confirm: "qwer" }); result.error.issues; ``` ```json /* [{ "code": "custom", "path": [ "confirm" ], "message": "Passwords don't match" }] */ ``` -------------------------------- ### Zod Union and Intersection Example Source: https://zod.dev/api?id=error Demonstrates creating a Zod intersection type from two union types. ```typescript const a = z.union([z.number(), z.string()]); const b = z.union([z.number(), z.boolean()]); const c = z.intersection(a, b); type c = z.infer; // => number ``` -------------------------------- ### Register Metadata using `.meta()` Method Source: https://zod.dev/metadata?id=registries The `.meta()` method offers a convenient way to register metadata directly with a schema instance, associating it with `z.globalRegistry`. ```typescript const emailSchema = z.email().meta({ id: "email_address", title: "Email address", description: "Please enter a valid email address", }); ``` -------------------------------- ### Async Transform Example Source: https://zod.dev/api?id=apply Transforms can be asynchronous. If using async transforms, you must use `.parseAsync` or `.safeParseAsync` for parsing. ```typescript const idToUser = z .string() .transform(async (id) => { // fetch user from database return db.getUserById(id); }); const user = await idToUser.parseAsync("abc123"); ``` -------------------------------- ### Displaying Custom Error Path Source: https://zod.dev/api?id=path This example shows how the `path` option affects the structure of the validation error issues. ```typescript const result = passwordForm.safeParse({ password: "asdf", confirm: "qwer" }); result.error.issues; ``` -------------------------------- ### Basic Schema Input/Output Types Source: https://zod.dev/codecs?id=base64tobytes Demonstrates the input and output types for a basic Zod string schema, showing that they are identical. ```typescript const schema = z.string(); type Input = z.input; // string type Output = z.output; // string schema.parse("asdf"); // => "asdf" schema.decode("asdf"); // => "asdf" schema.encode("asdf"); // => "asdf" ``` -------------------------------- ### Validate Booleans with Zod Source: https://zod.dev/api?id=zpartialrecord Use `z.boolean()` to validate true or false values. Examples show direct parsing. ```typescript z.boolean().parse(true); ``` ```typescript z.boolean().parse(false); ``` -------------------------------- ### Cloning Schemas with .clone() Source: https://zod.dev/packages/mini?id=brand Shows how to create an identical clone of a Zod Mini schema using the .clone() method, optionally providing a new definition. ```typescript const mySchema = z.string() mySchema.clone(mySchema._zod.def); ``` -------------------------------- ### TypeScript Discriminated Union Example Source: https://zod.dev/api?id=booleans Illustrates a discriminated union type in TypeScript for handling different result statuses. ```typescript type MyResult = | { status: "success"; data: string } | { status: "failed"; error: string }; function handleResult(result: MyResult){ if(result.status === "success"){ result.data; // string } else { result.error; // string } } ``` -------------------------------- ### Basic Zod Schema Input/Output Source: https://zod.dev/codecs?id=how-encoding-works Demonstrates that for basic schemas like z.string(), the input and output types are identical, making parse, decode, and encode functionally the same. ```typescript const schema = z.string(); type Input = z.input; // string type Output = z.output; // string schema.parse("asdf"); // => "asdf" schema.decode("asdf"); // => "asdf" schema.encode("asdf"); // => "asdf" ``` -------------------------------- ### UUID Validation Source: https://zod.dev/api?id=unknown Validate Universally Unique Identifiers (UUIDs) with Zod, including support for specific versions and GUIDs. ```APIDOC ### UUIDs To validate UUIDs: ```javascript z.uuid(); ``` To specify a particular UUID version: ```javascript // supports "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8" z.uuid({ version: "v4" }); // for convenience z.uuidv4(); z.uuidv6(); z.uuidv7(); ``` The RFC 9562/4122 UUID spec requires the first two bits of byte 8 to be `10`. Other UUID-like identifiers do not enforce this constraint. To validate any UUID-like identifier: ```javascript z.guid(); ``` ``` -------------------------------- ### Basic Zod Schema Input/Output Source: https://zod.dev/codecs?id=isodatetimetodate Demonstrates that for simple schemas like strings, the input and output types are identical, and parse, decode, and encode operations yield the same result. ```typescript const schema = z.string(); schema.parse("asdf"); // => "asdf" schema.decode("asdf"); // => "asdf" schema.encode("asdf"); // => "asdf" ```