### Installation Source: https://v3.zod.dev/?id=zodtype-with-zodeffects Instructions on how to install Zod, including requirements and installation via npm. ```APIDOC ## Installation ### Description Instructions for installing Zod, including prerequisites and the npm installation command. ### Requirements - Node.js (version not specified, but generally recent versions are recommended) - npm or yarn package manager ### From `npm` To install Zod using npm, run the following command in your project's terminal: ```bash npm install zod ``` Or using yarn: ```bash yarn add zod ``` ``` -------------------------------- ### Install Zod with npm Source: https://v3.zod.dev Install Zod using npm. Also shows installation commands for Deno, Yarn, Bun, and pnpm. ```bash npm install zod # npm deno add npm:zod # deno yarn add zod # yarn bun add zod # bun pnpm add zod # pnpm ``` -------------------------------- ### Install Zod Canary Version Source: https://v3.zod.dev Install the canary version of Zod from npm. Also shows installation commands for Deno, Yarn, Bun, and pnpm. ```bash npm install zod@canary # npm deno add npm:zod@canary # deno yarn add zod@canary # yarn bun add zod@canary # bun pnpm add zod@canary # pnpm ``` -------------------------------- ### Install Zod with npm Source: https://v3.zod.dev/?id=zod-to-x Install Zod using npm or other package managers. The canary version is available for every commit. ```bash npm install zod # npm deno add npm:zod # deno yarn add zod # yarn bun add zod # bun pnpm add zod # pnpm ``` ```bash npm install zod@canary # npm deno add npm:zod@canary # deno yarn add zod@canary # yarn bun add zod@canary # bun pnpm add zod@canary # pnpm ``` -------------------------------- ### Basic Usage Source: https://v3.zod.dev/?id=zodtype-with-zodeffects A simple example demonstrating how to use Zod to define a schema and parse data. ```APIDOC ## Basic Usage ### Description This section demonstrates the fundamental usage of Zod by defining a simple schema and parsing data against it. ### Example ```typescript import { z } from "zod"; // Define a schema for a User object const UserSchema = z.object({ name: z.string(), age: z.number().positive(), email: z.string().email() }); // Infer the TypeScript type from the schema // type User = z.infer; // Example data const userData = { name: "Alice", age: 30, email: "alice@example.com" }; // Parse the data using the schema try { const user = UserSchema.parse(userData); console.log("Parsed user data:", user); } catch (error) { console.error("Validation error:", error); } // Example of invalid data const invalidUserData = { name: "Bob", age: -5, email: "bob-at-example.com" }; try { UserSchema.parse(invalidUserData); } catch (error) { console.error("Validation error for invalid data:", error); } ``` ``` -------------------------------- ### Zod Primitive Coercion Examples Source: https://v3.zod.dev/?id=zod-to-x Demonstrates Zod's built-in coercion for primitive types using JavaScript's native constructors. ```typescript 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) ``` -------------------------------- ### Datetime Validation Source: https://v3.zod.dev Detailed explanation and examples for `z.string().datetime()`. ```APIDOC ## Datetimes The `z.string().datetime()` method validates ISO 8601 strings. By default, it enforces UTC with the 'Z' timezone and allows arbitrary sub-second precision. ### Default Behavior ```javascript const datetime = z.string().datetime(); datetime.parse("2020-01-01T00:00:00Z"); // pass datetime.parse("2020-01-01T00:00:00.123Z"); // pass datetime.parse("2020-01-01T00:00:00.123456Z"); // pass (arbitrary precision) datetime.parse("2020-01-01T00:00Z"); // pass (hours and minutes only) datetime.parse("2020-01-01T00:00:00+02:00"); // fail (no offsets allowed by default) ``` ### Allowing Timezone Offsets Set the `offset` option to `true` to allow timezone offsets. ```javascript const datetimeWithOffset = z.string().datetime({ offset: true }); datetimeWithOffset.parse("2020-01-01T00:00:00+02:00"); // pass datetimeWithOffset.parse("2020-01-01T00:00+02:00"); // pass datetimeWithOffset.parse("2020-01-01T00:00:00.123+02:00"); // pass (millis optional) datetimeWithOffset.parse("2020-01-01T00:00:00.123+0200"); // pass (millis optional) datetimeWithOffset.parse("2020-01-01T00:00:00.123+02"); // pass (only offset hours) datetimeWithOffset.parse("2020-01-01T00:00:00Z"); // pass (Z still supported) ``` ### Allowing Local (Timezone-less) Datetimes Use the `local` flag to allow unqualified (timezone-less) datetimes. ```javascript const localDatetime = z.string().datetime({ local: true }); schema.parse("2020-01-01T00:00:00"); // pass schema.parse("2020-01-01T00:00"); // pass ``` ### Constraining Precision You can additionally constrain the allowable `precision` for sub-second values. ```javascript const preciseDatetime = z.string().datetime({ precision: 3 }); preciseDatetime.parse("2020-01-01T00:00:00.123Z"); // pass preciseDatetime.parse("2020-01-01T00:00:00Z"); // fail preciseDatetime.parse("2020-01-01T00:00Z"); // fail preciseDatetime.parse("2020-01-01T00:00:00.123456Z"); // fail ``` ``` -------------------------------- ### Coercing String Primitive Source: https://v3.zod.dev Example of coercing various input types to a string using `z.coerce.string()`. ```typescript const schema = z.coerce.string(); schema.parse("tuna"); // => "tuna" schema.parse(12); // => "12" ``` -------------------------------- ### Interleaving Transforms and Refinements Source: https://v3.zod.dev/?id=zod-to-x Transforms and refinements can be chained in any order and are executed sequentially. This example converts a name to uppercase, checks its length, formats a greeting, and checks for exclamation marks. ```typescript const nameToGreeting = z .string() .transform((val) => val.toUpperCase()) .refine((val) => val.length > 15) .transform((val) => `Hello ${val}`) .refine((val) => val.indexOf("!") === -1); ``` -------------------------------- ### Make a String Schema Optional Source: https://v3.zod.dev Use `z.optional()` or the `.optional()` method to create a schema that accepts a string or undefined. Use `z.infer` to get the union type. ```typescript const schema = z.optional(z.string()); schema.parse(undefined); // => returns undefined type A = z.infer; // string | undefined ``` ```typescript const user = z.object({ username: z.string().optional(), }); type C = z.infer; // { username?: string | undefined }; ``` -------------------------------- ### Email to Domain Transformation Source: https://v3.zod.dev/?id=zod-to-x Apply string methods like `.email()` before `.transform()` to ensure validation occurs first. This example extracts the domain from an email address. ```typescript const emailToDomain = z .string() .email() .transform((val) => val.split("@")[1]); emailToDomain.parse("colinhacks@example.com"); // => example.com ``` -------------------------------- ### Zod Literal Schema Examples Source: https://v3.zod.dev/?id=zod-to-x Define literal schemas for exact string, number, bigint, boolean, and symbol values. ```typescript 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.literal(terrificSymbol); // retrieve literal value tuna.value; // "tuna" ``` -------------------------------- ### Add schema descriptions Source: https://v3.zod.dev/?id=zodtype-with-zodeffects Use .describe() to attach metadata to a schema, which is useful for tools like JSON Schema generators. ```typescript const documentedString = z .string() .describe("A useful bit of text, if you know what to do with it."); documentedString.description; // A useful bit of text… ``` -------------------------------- ### Basic String Schema Validation with Zod Source: https://v3.zod.dev/?id=zod-to-x Create and validate string schemas using Zod. Demonstrates both throwing errors on failure and safe parsing. ```typescript 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 } ``` -------------------------------- ### Schema Methods: `.describe()` Source: https://v3.zod.dev/?id=zodtype-with-zodeffects The `.describe()` method adds a description to a schema, which can be useful for documentation generation or custom error messages. ```APIDOC ## Schema Methods: `.describe()` ### Description The `.describe()` method allows you to attach a descriptive string to a Zod schema. This description can be helpful for generating documentation or providing more context in error messages. ### Method `.describe(description: string): Schema` ### Parameters - **description** (string) - The description to associate with the schema. ### Request Example ```typescript import { z } from "zod"; const EmailSchema = z.string().email().describe("A valid email address."); const data = "test@example.com"; try { const email = EmailSchema.parse(data); console.log(email); // The description itself isn't directly used in parsing, but can be accessed // console.log(EmailSchema.description); // "A valid email address." } catch (error) { console.error(error); } ``` ### Response Example (Success) ```json "test@example.com" ``` ``` -------------------------------- ### Schema Methods: `.promise()` Source: https://v3.zod.dev/?id=zodtype-with-zodeffects The `.promise()` method creates a schema that validates a Promise. ```APIDOC ## Schema Methods: `.promise()` ### Description The `.promise()` method creates a schema that validates a `Promise`. It ensures that the input is a Promise and can optionally validate the resolved value of the Promise. ### Method `z.promise(schema?: ZodSchema): ZodPromise>` ### Parameters - **schema** (ZodSchema, optional) - A schema to validate the resolved value of the Promise. ### Request Example ```typescript import { z } from "zod"; // Schema for a Promise that resolves to a number const NumberPromiseSchema = z.promise(z.number()); const validPromise = Promise.resolve(123); const invalidPromise = Promise.resolve("hello"); const notAPromise = 123; try { const result1 = await NumberPromiseSchema.parseAsync(validPromise); console.log(result1); // 123 } catch (error) { console.error(error); } try { await NumberPromiseSchema.parseAsync(invalidPromise); } catch (error) { console.error(error); // Output: ZodError: [ { code: 'invalid_type', expected: 'number', received: 'string', path: [], message: 'Invalid input' } ] } try { await NumberPromiseSchema.parseAsync(notAPromise); } catch (error) { console.error(error); // Output: ZodError: [ { code: 'invalid_type', expected: 'ZodPromise', received: 'number', path: [], message: 'Invalid input' } ] } // Schema for a Promise without validating the resolved value const AnyPromiseSchema = z.promise(); try { const result2 = await AnyPromiseSchema.parseAsync(Promise.resolve({ data: "some value" })); console.log(result2); // { data: 'some value' } } catch (error) { console.error(error); } ``` ``` -------------------------------- ### Schema Methods: `.default()` Source: https://v3.zod.dev/?id=zodtype-with-zodeffects The `.default()` method sets a default value for a schema if the input data is missing or undefined. ```APIDOC ## Schema Methods: `.default()` ### Description The `.default()` method allows you to specify a default value for a schema. If the input data for this field is `undefined` during parsing, the default value will be used instead. ### Method `.default(defaultValue: T): Schema` ### Parameters - **defaultValue** (T) - The value to use if the input is `undefined`. ### Request Example ```typescript import { z } from "zod"; const UserSchema = z.object({ name: z.string(), age: z.number().default(18) }); const user1 = UserSchema.parse({ name: "Alice" }); console.log(user1); // { name: 'Alice', age: 18 } const user2 = UserSchema.parse({ name: "Bob", age: 30 }); console.log(user2); // { name: 'Bob', age: 30 } const user3 = UserSchema.parse({ name: "Charlie", age: undefined }); console.log(user3); // { name: 'Charlie', age: 18 } ``` ### Response Example (Success) ```json { "name": "Alice", "age": 18 } ``` ``` -------------------------------- ### Core Schema Methods: Parse, ParseAsync, SafeParse Source: https://v3.zod.dev/?id=zodtype-with-zodeffects Understand how to validate and extract data using Zod's core parsing methods. ```APIDOC ## Schema Methods All Zod schemas provide core methods for parsing and validation. ### `.parse(data: unknown): T` Validates `data` against the schema. Returns the validated data with full type information if successful, otherwise throws an error. *Note: The returned value is a deep clone of the input.* ```javascript const stringSchema = z.string(); stringSchema.parse("fish"); // => returns "fish" stringSchema.parse(12); // throws error ``` ### `.parseAsync(data: unknown): Promise` Use this method for schemas involving asynchronous refinements or transforms. It returns a Promise that resolves with the validated data or rejects with an error. ```javascript const stringSchema = z.string().refine(async (val) => val.length <= 8); await stringSchema.parseAsync("hello"); // => returns "hello" await stringSchema.parseAsync("hello world"); // => throws error ``` ### `.safeParse(data: unknown): { success: true; data: T; } | { success: false; error: ZodError; }` Performs validation without throwing errors. Returns an object indicating success or failure. On success, it contains the parsed `data`. On failure, it contains a `ZodError` instance. ```javascript stringSchema.safeParse(12); // => { success: false; error: ZodError } stringSchema.safeParse("billie"); // => { success: true; data: 'billie' } ``` **Handling Results:** The result is a discriminated union, allowing for convenient error handling: ```javascript const result = stringSchema.safeParse("billie"); if (!result.success) { // handle error result.error; } else { // use data result.data; } ``` ``` -------------------------------- ### Schema Methods: `.pipe()` Source: https://v3.zod.dev/?id=zodtype-with-zodeffects The `.pipe()` method chains multiple schemas together, passing the output of one schema as the input to the next. ```APIDOC ## Schema Methods: `.pipe()` ### Description The `.pipe()` method allows you to chain multiple Zod schemas together. The output of the first schema is passed as the input to the second schema, and so on. This is useful for applying multiple transformations or validations in sequence. ### Method `.pipe(nextSchema: ZodSchema): ZodPipeline>` ### Parameters - **nextSchema** (ZodSchema) - The next schema in the pipeline. ### Request Example ```typescript import { z } from "zod"; const PositiveStringSchema = z.string().min(1).transform(str => parseInt(str, 10)).pipe(z.number().positive()); const validData = "10"; const invalidData = "-5"; const nonNumericData = "abc"; try { const result1 = PositiveStringSchema.parse(validData); console.log(result1); // 10 } catch (error) { console.error(error); } try { PositiveStringSchema.parse(invalidData); } catch (error) { console.error(error); // Output: ZodError: [ { code: 'too_small', minimum: 0, type: 'number', inclusive: true, message: 'Number must be greater than 0', path: [], issues: [ [Object] ] } ] } try { PositiveStringSchema.parse(nonNumericData); } catch (error) { console.error(error); // Output: ZodError: [ { code: 'invalid_type', expected: 'string', received: 'number', path: [], message: 'Invalid input' } ] } ``` ### Response Example (Success) ```json 10 ``` ``` -------------------------------- ### Create Promise Schema with .promise Source: https://v3.zod.dev/?id=zod-to-x The .promise() method creates a schema for a Promise of a specific type. It is a shorthand for z.promise(schema). ```typescript const stringPromise = z.string().promise(); // Promise // equivalent to z.promise(z.string()); ``` -------------------------------- ### Adding Schema Description with `.describe()` Source: https://v3.zod.dev/?id=zod-to-x Use `.describe()` to add a `description` property to a schema, useful for documentation generation tools like `zod-to-json-schema`. ```typescript const documentedString = z .string() .describe("A useful bit of text, if you know what to do with it."); documentedString.description; // A useful bit of text… ``` -------------------------------- ### Custom Schemas and Preprocessing Source: https://v3.zod.dev/?id=zod-to-x Utilities for creating custom validation logic and applying transformations before parsing. ```APIDOC ## Custom Schemas and Preprocessing ### z.preprocess(transform, schema) Applies a transformation to the input before validation occurs. Useful for type coercion. ### z.custom(validator, error) Creates a schema for types not supported natively by Zod. ### Example ```typescript const px = z.custom<`${number}px`>((val) => { return typeof val === "string" ? /^\d+px$/.test(val) : false; }); ``` ``` -------------------------------- ### Zod Array Schemas Source: https://v3.zod.dev Documentation for creating and manipulating array schemas in Zod, including element types and size constraints. ```APIDOC ## Zod Array Schemas ### Description Defines schemas for arrays, allowing validation of elements and array properties. ### Methods #### `.array(): ZodArray>` - **Description**: Creates an array schema where each element conforms to the current schema. - **Returns**: `ZodArray>` - A new array schema. #### `.element(schema: ZodSchema): ZodArray>` - **Description**: Defines the schema for elements within an array. - **Parameters**: - `schema` (ZodSchema) - The schema for array elements. - **Returns**: `ZodArray>` - A new array schema with specified element type. #### `.nonempty(): ZodNonEmptyArray>` - **Description**: Ensures the array is not empty. - **Returns**: `ZodNonEmptyArray>` - A new array schema that cannot be empty. #### `.min(minLength: number): ZodArray>` - **Description**: Sets the minimum length for the array. - **Parameters**: - `minLength` (number) - The minimum allowed length. - **Returns**: `ZodArray>` - A new array schema with a minimum length constraint. #### `.max(maxLength: number): ZodArray>` - **Description**: Sets the maximum length for the array. - **Parameters**: - `maxLength` (number) - The maximum allowed length. - **Returns**: `ZodArray>` - A new array schema with a maximum length constraint. #### `.length(exactLength: number): ZodArray>` - **Description**: Sets the exact length for the array. - **Parameters**: - `exactLength` (number) - The exact required length. - **Returns**: `ZodArray>` - A new array schema with an exact length constraint. ### Request Example ```javascript const numberArraySchema = z.array(z.number()); const data = [1, 2, 3, 4, 5]; const result = numberArraySchema.safeParse(data); console.log(result); const nonEmptySchema = z.array(z.string()).nonempty().min(2); const nonEmptyData = ["a", "b"]; console.log(nonEmptySchema.safeParse(nonEmptyData)); const exactLengthSchema = z.array(z.boolean()).length(3); const exactLengthData = [true, false, true]; console.log(exactLengthSchema.safeParse(exactLengthData)); ``` ### Response Example ```json { "success": true, "data": [ 1, 2, 3, 4, 5 ] } ``` ``` -------------------------------- ### Schema Methods: `.catch()` Source: https://v3.zod.dev/?id=zodtype-with-zodeffects The `.catch()` method provides a fallback value if parsing fails, similar to `.default()` but specifically for error scenarios. ```APIDOC ## Schema Methods: `.catch()` ### Description The `.catch()` method allows you to specify a fallback value that will be returned if the schema parsing fails. This is useful for providing a default or safe value when validation errors occur, without needing to use a `try...catch` block. ### Method `.catch(catchValue: T): Schema` ### Parameters - **catchValue** (T) - The value to return if parsing fails. ### Request Example ```typescript import { z } from "zod"; const ConfigSchema = z.object({ port: z.number() }).catch({ port: 8080 }); const validConfig = ConfigSchema.parse({ port: 3000 }); console.log(validConfig); // { port: 3000 } const invalidConfig = ConfigSchema.parse({}); // Missing 'port' console.log(invalidConfig); // { port: 8080 } const anotherInvalidConfig = ConfigSchema.parse({ port: "not a number" }); // Invalid type for 'port' console.log(anotherInvalidConfig); // { port: 8080 } ``` ### Response Example (Success) ```json { "port": 3000 } ``` ### Response Example (Fallback on Error) ```json { "port": 8080 } ``` ``` -------------------------------- ### Schema Methods: `.nullish()` Source: https://v3.zod.dev/?id=zodtype-with-zodeffects The `.nullish()` method makes a schema accept both `null` and `undefined` as valid values. ```APIDOC ## Schema Methods: `.nullish()` ### Description The `.nullish()` method makes a schema accept both `null` and `undefined` as valid values. It's a convenient shorthand for `.nullable().optional()` or `.or(z.literal(null)).or(z.literal(undefined))`. ### Method `.nullish(): Schema` ### Request Example ```typescript import { z } from "zod"; const UserSchema = z.object({ name: z.string(), age: z.number().nullish() }); const user1 = UserSchema.parse({ name: "Alice", age: 30 }); console.log(user1); // { name: 'Alice', age: 30 } const user2 = UserSchema.parse({ name: "Bob", age: null }); console.log(user2); // { name: 'Bob', age: null } const user3 = UserSchema.parse({ name: "Charlie", age: undefined }); console.log(user3); // { name: 'Charlie', age: undefined } const user4 = UserSchema.parse({ name: "David" }); console.log(user4); // { name: 'David', age: undefined } ``` ### Response Example (Success) ```json { "name": "Alice", "age": 30 } ``` ### Response Example (Nullish Field is Null) ```json { "name": "Bob", "age": null } ``` ### Response Example (Nullish Field is Undefined) ```json { "name": "Charlie", "age": undefined } ``` ``` -------------------------------- ### Simulate Nominal Typing with .brand Source: https://v3.zod.dev/?id=zod-to-x The .brand() method attaches a static-only brand to a schema, allowing simulation of nominal typing. This prevents structurally identical but unbranded types from being assignable. ```typescript type Cat = { name: string }; type Dog = { name: string }; const petCat = (cat: Cat) => {}; const fido: Dog = { name: "fido" }; petCat(fido); // works fine ``` ```typescript const Cat = z.object({ name: z.string() }).brand<"Cat">(); type Cat = z.infer; const petCat = (cat: Cat) => {}; // this works const simba = Cat.parse({ name: "simba" }); petCat(simba); // this doesn't petCat({ name: "fido" }); ``` ```typescript const Cat = z.object({ name: z.string() }).brand<"Cat">(); type Cat = z.infer; // {name: string} & {[symbol]: "Cat"} ``` -------------------------------- ### Asynchronous Safe Parsing Source: https://v3.zod.dev/?id=zodtype-with-zodeffects Demonstrates the use of .safeParseAsync and its alias .spa for asynchronous validation of data against a Zod schema. ```APIDOC ## Asynchronous Safe Parsing ### Description An asynchronous version of `safeParse` for validating data. ### Method `safeParseAsync` or `spa` ### Endpoint N/A (Client-side or server-side JavaScript method) ### Parameters - `data` (any) - Required - The data to parse. ### Request Example ```javascript await stringSchema.safeParseAsync("billie"); // or await stringSchema.spa("billie"); ``` ### Response Returns a `SafeParseReturnType` object indicating success or failure with parsed data or errors. ``` -------------------------------- ### Use a record schema for user storage Source: https://v3.zod.dev/?id=zod-to-x Demonstrates assigning and validating user objects within a Zod record schema. Shows a successful assignment and a TypeError for an invalid assignment. ```typescript const userStore: UserStore = {}; userStore["77d2586b-9e8e-4ecf-8b21-ea7e0530eadd"] = { name: "Carlotta", }; // passes userStore["77d2586b-9e8e-4ecf-8b21-ea7e0530eadd"] = { whatever: "Ice cream sundae", }; // TypeError ``` -------------------------------- ### Create a custom schema Source: https://v3.zod.dev/?id=zod-to-x Define a schema for types not supported by Zod using z.custom. ```typescript const px = z.custom<`${number}px`>((val) => { return typeof val === "string" ? /^\d+px$/.test(val) : false; }); type px = z.infer; // `${number}px` px.parse("42px"); // "42px" px.parse("42vw"); // throws; ``` -------------------------------- ### Define array schemas Source: https://v3.zod.dev/?id=zod-to-x Create array schemas using z.array() or .array(), noting that method order affects the resulting type. ```typescript const stringArray = z.array(z.string()); // equivalent const stringArray = z.string().array(); ``` ```typescript z.string().optional().array(); // (string | undefined)[] z.string().array().optional(); // string[] | undefined ``` -------------------------------- ### Schema Methods: `.brand()` Source: https://v3.zod.dev/?id=zodtype-with-zodeffects The `.brand()` method creates a branded type, allowing you to create distinct types from the same underlying primitive or object structure. ```APIDOC ## Schema Methods: `.brand()` ### Description The `.brand()` method allows you to create branded types in Zod. Branded types are distinct types that share the same underlying structure but are treated as different types by TypeScript's type system. This is useful for adding semantic meaning to data, like distinguishing between a raw string and a `UserID` string. ### Method `.brand(): ZodBranded` ### Parameters - **Brand** (string | number | symbol) - A unique symbol or string to identify the brand. ### Request Example ```typescript import { z } from "zod"; // Define a branded type for UserID const UserID = z.string().brand<'UserID'>(); // Define a branded type for ProductID const ProductID = z.string().brand<'ProductID'>(); // Infer TypeScript types // type UserIDType = z.infer; // string // type ProductIDType = z.infer; // string // Branded types are structurally compatible but distinct at the type level const userId: UserIDType = "user-123" as UserIDType; const productId: ProductIDType = "prod-abc" as ProductIDType; // Zod validation works with the underlying type const parsedUserId = UserID.parse("user-456"); console.log(parsedUserId); // TypeScript will prevent assigning one branded type to another directly // const invalidAssignment: UserIDType = productId; // Error: Type 'ProductIDType' is not assignable to type 'UserIDType'. // You can use branded types in objects const UserSchema = z.object({ id: UserID, name: z.string() }); const user = UserSchema.parse({ id: "user-789", name: "Alice" }); console.log(user); ``` ### Response Example (Success) ```json { "id": "user-789", "name": "Alice" } ``` ``` -------------------------------- ### Zod Schema Methods Source: https://v3.zod.dev/?id=zodtype-with-zodeffects A collection of utility methods for modifying and chaining Zod schemas. ```APIDOC ## .catch ### Description Provides a fallback value or function to be returned if parsing fails. ### Usage - `schema.catch(value)`: Returns the provided value on error. - `schema.catch((ctx) => value)`: Executes a function to generate a value on error, receiving a `ctx` object with the error. ## .optional, .nullable, .nullish ### Description Convenience methods to modify schema requirements. - `.optional()`: Allows `undefined`. - `.nullable()`: Allows `null`. - `.nullish()`: Allows both `null` and `undefined`. ## .array, .promise ### Description Wraps the schema in an array or promise type. - `.array()`: Returns `z.array(schema)`. - `.promise()`: Returns `z.promise(schema)`. ## .or, .and ### Description Creates union or intersection types. - `.or(schema)`: Creates a union (OR). - `.and(schema)`: Creates an intersection (AND). ## .brand ### Description Simulates nominal typing by attaching a brand to the inferred type. This is a static-only construct and does not affect runtime parsing. ## .readonly ### Description Returns a schema that calls `Object.freeze()` on the result after parsing and marks the inferred type as readonly. ## .pipe ### Description Chains schemas into a validation pipeline, useful for validating results after transformations. ``` -------------------------------- ### Create a record schema for users Source: https://v3.zod.dev/?id=zod-to-x Use z.record to define a schema for key-value pairs where keys are strings and values conform to a specified object schema. Useful for dictionaries or caches. ```typescript const User = z.object({ name: z.string() }); const UserStore = z.record(z.string(), User); type UserStore = z.infer; // => Record ``` -------------------------------- ### Writing generic functions with Zod Source: https://v3.zod.dev/?id=zod-to-x Demonstrates the incorrect approach of using z.ZodType and the preferred approach using z.ZodTypeAny to preserve schema subclass information. ```typescript function inferSchema(schema: z.ZodType) { return schema; } ``` ```typescript inferSchema(z.string()); // => ZodType ``` ```typescript function inferSchema(schema: T) { return schema; } inferSchema(z.string()); // => ZodString ``` -------------------------------- ### Zod Preprocess Source: https://v3.zod.dev/?id=zodtype-with-zodeffects Apply transformations to data before Zod validation occurs. ```APIDOC ## Preprocess Zod's `.preprocess()` method allows you to transform input data *before* validation. ### Usage This is useful for type coercion or other initial data cleaning. ```javascript const castToString = z.preprocess((val) => String(val), z.string()); ``` `.preprocess()` returns a `ZodEffects` instance, which handles preprocessing, refinements, and transforms. ``` -------------------------------- ### Core Schema Methods Source: https://v3.zod.dev Utilize essential Zod schema methods for parsing, asynchronous parsing, and safe parsing of data. ```APIDOC ## Schema Methods All Zod schemas provide core methods for data validation and parsing. ### `.parse` Method Validates data against the schema. Throws an error if validation fails; otherwise, returns the validated data with full type information. **Signature:** `.parse(data: unknown): T` **Note:** The returned value is a deep clone of the input. ```javascript const stringSchema = z.string(); stringSchema.parse("fish"); // => returns "fish" stringSchema.parse(12); // throws error ``` ### `.parseAsync` Method Used for schemas with asynchronous refinements or transforms. Returns a Promise that resolves with the validated data or rejects with an error. **Signature:** `.parseAsync(data:unknown): Promise` ```javascript const stringSchema = z.string().refine(async (val) => val.length <= 8); await stringSchema.parseAsync("hello"); // => returns "hello" await stringSchema.parseAsync("hello world"); // => throws error ``` ### `.safeParse` Method Performs validation without throwing errors. Returns an object indicating success or failure, including the parsed data or a `ZodError`. **Signature:** `.safeParse(data:unknown): { success: true; data: T; } | { success: false; error: ZodError; }` ```javascript stringSchema.safeParse(12); // => { success: false; error: ZodError } stringSchema.safeParse("billie"); // => { success: true; data: 'billie' } ``` **Handling Results:** The result is a discriminated union, allowing for convenient error handling: ```javascript const result = stringSchema.safeParse("billie"); if (!result.success) { // handle error result.error; } else { // use parsed data result.data; } ``` ``` -------------------------------- ### Promise Schema Source: https://v3.zod.dev/?id=zod-to-x The .promise() method creates a schema for promise types. ```APIDOC ## .promise() ### Description A convenience method for promise types: ### Request Example ```javascript const stringPromise = z.string().promise(); // Promise // equivalent to z.promise(z.string()); ``` ``` -------------------------------- ### Preprocessing Data Source: https://v3.zod.dev Apply transformations to input data before Zod performs validation using `z.preprocess()`. ```APIDOC ## Preprocess `z.preprocess()` allows you to transform input data before Zod's validation and transformation steps. ### Basic Preprocessing ```javascript const castToString = z.preprocess((val) => String(val), z.string()); ``` `z.preprocess()` returns a `ZodEffects` instance, which handles preprocessing, refinements, and transforms. ``` -------------------------------- ### Branded Types Source: https://v3.zod.dev/?id=zod-to-x The .brand() method allows simulating nominal typing by attaching a static-only brand to a schema's inferred type. ```APIDOC ## .brand() ### Description `.brand() => ZodBranded` TypeScript's type system is structural, which means that any two types that are structurally equivalent are considered the same. In some cases, its can be desirable to simulate _nominal typing_ inside TypeScript. For instance, you may wish to write a function that only accepts an input that has been validated by Zod. This can be achieved with _branded types_ (AKA _opaque types_). ### Request Example ```javascript const Cat = z.object({ name: z.string() }).brand<"Cat">(); type Cat = z.infer; const petCat = (cat: Cat) => {}; // this works const simba = Cat.parse({ name: "simba" }); petCat(simba); // this doesn't petCat({ name: "fido" }); ``` Under the hood, this works by attaching a "brand" to the inferred type using an intersection type. This way, plain/unbranded data structures are no longer assignable to the inferred type of the schema. ```javascript const Cat = z.object({ name: z.string() }).brand<"Cat">(); type Cat = z.infer; // {name: string} & {[symbol]: "Cat"} ``` Note that branded types do not affect the runtime result of `.parse`. It is a static-only construct. ``` -------------------------------- ### Schema Methods Source: https://v3.zod.dev/?id=zod-to-x Core methods available on all Zod schemas for data validation and parsing. ```APIDOC ## Schema Methods ### .parse(data) Validates data and returns the parsed value or throws an error. ### .parseAsync(data) Asynchronous version of parse, required for schemas with async refinements or transforms. ### .safeParse(data) Returns a discriminated union object indicating success or failure without throwing errors. ### Example ```typescript const result = stringSchema.safeParse("billie"); if (result.success) { console.log(result.data); } else { console.error(result.error); } ``` ``` -------------------------------- ### Zod Object Schema Methods Source: https://v3.zod.dev/?id=zodtype-with-zodeffects Methods to control object property requirements and handling of unknown keys. ```APIDOC ## Zod Object Methods ### .required() - Makes all properties required or specific properties required. ### .passthrough() - Allows unknown keys to pass through during parsing instead of being stripped. ### .strict() - Disallows unknown keys; throws a ZodError if unknown keys are present. ### .strip() - Resets object schema to default behavior (stripping unrecognized keys). ### .catchall(schema) - Validates all unknown keys against the provided schema. ``` -------------------------------- ### Apply preprocessing to input Source: https://v3.zod.dev/?id=zod-to-x Use z.preprocess to transform input data before validation occurs. ```typescript const castToString = z.preprocess((val) => String(val), z.string()); ``` -------------------------------- ### Extracting input and output types for transforms Source: https://v3.zod.dev/?id=zod-to-x Use z.input and z.output to distinguish between the input and output types of a schema containing transforms. ```typescript const stringToNumber = z.string().transform((val) => val.length); // ⚠️ Important: z.infer returns the OUTPUT type! type input = z.input; // string type output = z.output; // number // equivalent to z.output! type inferred = z.infer; // number ``` -------------------------------- ### Pick Properties from an Object Schema Source: https://v3.zod.dev Create a new object schema containing only specified properties using the `.pick()` method. The argument is an object where keys to keep are set to `true`. ```typescript const Recipe = z.object({ id: z.string(), name: z.string(), ingredients: z.array(z.string()), }); const JustTheName = Recipe.pick({ name: true }); type JustTheName = z.infer; // => { name: string } ``` -------------------------------- ### Create Array Schema with .array Source: https://v3.zod.dev/?id=zod-to-x The .array() method creates a schema for an array of a specific type. It is a shorthand for z.array(schema). ```typescript const stringArray = z.string().array(); // string[] // equivalent to z.array(z.string()); ``` -------------------------------- ### Custom Schemas Source: https://v3.zod.dev Create Zod schemas for any TypeScript type, including those not natively supported, using `z.custom()`. ```APIDOC ## Custom Schemas Use `z.custom()` to create schemas for any TypeScript type. ### Example: Pixel Value Schema ```javascript const px = z.custom<`${number}px`>((val) => { return typeof val === "string" ? /^d+px$/.test(val) : false; }); type px = z.infer; // `${number}px` px.parse("42px"); // "42px" px.parse("42vw"); // throws; ``` ### Schema Without Validation If no validation function is provided, `z.custom()` will allow any value, which can be unsafe. ```javascript z.custom<{ arg: string }>(); // performs no validation ``` ### Customizing Error Messages You can provide a custom error message as the second argument, similar to the `.refine` method's parameters. ```javascript z.custom<...>((val) => ..., "custom error message"); ``` ``` -------------------------------- ### JavaScript object keys are strings Source: https://v3.zod.dev/?id=zod-to-x Illustrates that JavaScript automatically casts all object keys to strings at runtime, explaining why Zod does not support numerical keys directly in z.record. ```javascript const testMap: { [k: number]: string } = { 1: "one", }; for (const key in testMap) { console.log(`${key}: ${typeof key}`); } // prints: `1: string` ``` -------------------------------- ### Create optional schemas Source: https://v3.zod.dev/?id=zod-to-x Use z.optional() or .optional() to allow undefined values in a schema. ```typescript const schema = z.optional(z.string()); schema.parse(undefined); // => returns undefined type A = z.infer; // string | undefined ``` ```typescript const user = z.object({ username: z.string().optional(), }); type C = z.infer; // { username?: string | undefined }; ``` ```typescript const stringSchema = z.string(); const optionalString = stringSchema.optional(); optionalString.unwrap() === stringSchema; // true ``` -------------------------------- ### Handle unknown object keys Source: https://v3.zod.dev/?id=zod-to-x Control how unrecognized keys are treated during parsing using .passthrough, .strict, or .catchall. ```typescript const person = z.object({ name: z.string(), }); person.parse({ name: "bob dylan", extraKey: 61, }); // => { name: "bob dylan" } // extraKey has been stripped ``` ```typescript person.passthrough().parse({ name: "bob dylan", extraKey: 61, }); // => { name: "bob dylan", extraKey: 61 } ``` ```typescript const person = z .object({ name: z.string(), }) .strict(); person.parse({ name: "bob dylan", extraKey: 61, }); // => throws ZodError ``` ```typescript const person = z .object({ name: z.string(), }) .catchall(z.number()); person.parse({ name: "bob dylan", validExtraKey: 61, // works fine }); person.parse({ name: "bob dylan", validExtraKey: false, // fails }); // => throws ZodError ``` -------------------------------- ### Extract parameters and return type from function schema Source: https://v3.zod.dev/?id=zod-to-x Retrieve the input and output schemas from an existing function schema. ```typescript myFunction.parameters(); // => ZodTuple<[ZodString, ZodNumber]> myFunction.returnType(); // => ZodBoolean ``` -------------------------------- ### Create Optional Schema with .optional Source: https://v3.zod.dev/?id=zod-to-x The .optional() method creates a schema that accepts the original type or undefined. It is a shorthand for z.optional(schema). ```typescript const optionalString = z.string().optional(); // string | undefined // equivalent to z.optional(z.string()); ``` -------------------------------- ### Schema Methods: `.array()` Source: https://v3.zod.dev/?id=zodtype-with-zodeffects The `.array()` method creates a schema that validates an array of a specific type. ```APIDOC ## Schema Methods: `.array()` ### Description The `.array()` method is used to create a schema that validates an array. It takes another Zod schema as an argument, which defines the type of elements within the array. ### Method `z.array(schema: ZodSchema): ZodArray>` ### Parameters - **schema** (ZodSchema) - The schema that defines the type of elements in the array. ### Request Example ```typescript import { z } from "zod"; const NumberArraySchema = z.array(z.number()); const validData = [1, 2, 3]; const invalidData = [1, "two", 3]; try { const result1 = NumberArraySchema.parse(validData); console.log(result1); // [ 1, 2, 3 ] } catch (error) { console.error(error); } try { NumberArraySchema.parse(invalidData); } catch (error) { console.error(error); // Output: ZodError: [ { code: 'invalid_type', expected: 'number', received: 'string', path: [ 1 ], message: 'Invalid input' } ] } const UserSchema = z.object({ name: z.string(), tags: z.array(z.string()) }); const userData = { name: "Alice", tags: ["typescript", "zod", "validation"] }; const user = UserSchema.parse(userData); console.log(user); ``` ### Response Example (Success) ```json [ 1, 2, 3 ] ``` ``` -------------------------------- ### Create nullable schemas Source: https://v3.zod.dev/?id=zod-to-x Use z.nullable() or .nullable() to allow null values in a schema. ```typescript const nullableString = z.nullable(z.string()); nullableString.parse("asdf"); // => "asdf" nullableString.parse(null); // => null ``` ```typescript const E = z.string().nullable(); // equivalent to nullableString type E = z.infer; // string | null ``` ```typescript const stringSchema = z.string(); const nullableString = stringSchema.nullable(); nullableString.unwrap() === stringSchema; // true ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.