Zod

TypeScript-first schema validation with static type inference

README

Zod logo

Zod

https://zod.dev

    TypeScript-first schema validation with static type inference


Zod CI statusCreated by Colin McDonnellLicensenpmstarsdiscord server

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



These docs have been translated into Chinese.


Table of contents


<!-- The full documentation is available both on the official documentation site (recommended) and inREADME.md.

Go to zod.js.org >> -->


  - Sponsors
  - Ecosystem
  - Node/npm
  - Deno
  - .shape
  - .keyof
  - .extend
  - .merge
  - .partial
  - .strict
  - .strip
  - .catchall
  - .element
  - .nonempty
  - JSON type
  - .parse
  - .refine
  - .default
  - .catch
  - .optional
  - .nullable
  - .nullish
  - .array
  - .promise
  - .or
  - .and
  - .brand
  - Joi
  - Yup
  - io-ts
  - Runtypes



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 (i.e. .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
deletype.com

Silver



Snaplet
snaplet.dev
Marcato Partners
Marcato Partners
marcatopartners.com
Trip
Trip

Seasoned Software
seasoned.cc

Interval
interval.com

Bronze



Brandon Bayer
@flybayer, creator of Blitz.js

Jiří Brabec
@brabeji

Alex Johansson
@alexdotjs

Adaptable
adaptable.io
Avana Wallet logo
Avana Wallet
avanawallet.com
Solana non-custodial wallet

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](https://github.com/trpc/trpc): Build end-to-end typesafe APIs without GraphQL.
- [@anatine/zod-nestjs](https://github.com/anatine/zod-plugins/tree/main/packages/zod-nestjs): Helper methods for using Zod in a NestJS project.
- [zod-endpoints](https://github.com/flock-community/zod-endpoints): Contract-first strictly typed endpoints with Zod. OpenAPI compatible.
- [domain-functions](https://github.com/SeasonedSoftware/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](https://github.com/ecyrbe/zodios): A typescript API client with runtime and compile time validation backed by axios and zod.
- [express-zod-api](https://github.com/RobinTail/express-zod-api): Build Express-based APIs with I/O schema validation and custom middlewares.

Form integrations


- [react-hook-form](https://github.com/react-hook-form/resolvers#zod): A first-party Zod resolver for React Hook Form.
- [zod-validation-error](https://github.com/causaly/zod-validation-error): Generate user-friendly error messages from ZodErrors
- [zod-formik-adapter](https://github.com/robertLichtnow/zod-formik-adapter): A community-maintained Formik adapter for Zod.
- [`react-zorm`](https://github.com/esamattis/react-zorm): Standalone `
` generation and validation for React using Zod.
- [zodix](https://github.com/rileytomasek/zodix): Zod utilities for FormData and URLSearchParams in Remix loaders and actions.

Zod to X


- [zod-to-ts](https://github.com/sachinraja/zod-to-ts): Generate TypeScript definitions from Zod schemas.
- [zod-to-json-schema](https://github.com/StefanTerdell/zod-to-json-schema): Convert your Zod schemas into JSON Schemas.
- [@anatine/zod-openapi](https://github.com/anatine/zod-plugins/tree/main/packages/zod-openapi): Converts a Zod schema to an OpenAPI v3.x SchemaObject.
- [zod-fast-check](https://github.com/DavidTimms/zod-fast-check): Generate fast-check arbitraries from Zod schemas.
- [zod-dto](https://github.com/kbkk/abitia/tree/master/packages/zod-dto): Generate Nest.js DTOs from a Zod schema.
- [fastify-type-provider-zod](https://github.com/turkerdev/fastify-type-provider-zod): Create Fastify type providers from Zod schemas.
- [zod-to-openapi](https://github.com/asteasolutions/zod-to-openapi): Generate full OpenAPI (Swagger) docs from Zod, including schemas, endpoints & parameters.
- [nestjs-graphql-zod](https://github.com/incetarik/nestjs-graphql-zod): Generates NestJS GraphQL model classes from Zod schemas. Provides GraphQL method decorators working with Zod schemas.

X to Zod


- [ts-to-zod](https://github.com/fabien0102/ts-to-zod): Convert TypeScript definitions into Zod schemas.
- [@runtyping/zod](https://github.com/johngeorgewright/runtyping/tree/master/packages/zod): Generate Zod from static types & JSON schema.
- [json-schema-to-zod](https://github.com/StefanTerdell/json-schema-to-zod): Convert your JSON Schemas into Zod schemas. Live demo.
- [json-to-zod](https://github.com/rsinohara/json-to-zod): Convert JSON objects into Zod schemas. Live demo.
- [graphql-codegen-typescript-validation-schema](https://github.com/Code-Hex/graphql-codegen-typescript-validation-schema): GraphQL Code Generator plugin to generate form validation schema from your GraphQL schema
- [zod-prisma](https://github.com/CarterGrimmeisen/zod-prisma): Generate Zod schemas from your Prisma schema.
- [Supervillain](https://github.com/Southclaws/supervillain): Generate Zod schemas from your Go structs.
- [prisma-zod-generator](https://github.com/omar-dulaimi/prisma-zod-generator): Emit Zod schemas from your Prisma schema.
- [prisma-trpc-generator](https://github.com/omar-dulaimi/prisma-trpc-generator): Emit fully implemented tRPC routers and their validation schemas using Zod.

Mocking


- [@anatine/zod-mock](https://github.com/anatine/zod-plugins/tree/main/packages/zod-mock): Generate mock data from a Zod schema. Powered by faker.js.
- [zod-mocking](https://github.com/dipasqualew/zod-mocking): Generate mock data from your Zod schemas.

Powered by Zod


- [slonik](https://github.com/gajus/slonik/tree/gajus/add-zod-validation-backwards-compatible#runtime-validation-and-static-type-inference): Node.js Postgres client with strong Zod integration.
- [soly](https://github.com/mdbetancourt/soly): Create CLI applications with zod.
- [zod-xlsx](https://github.com/sidwebworks/zod-xlsx): A xlsx based resource validator using Zod schemas.

Installation


Requirements


- TypeScript 4.1+!
- You must enable strict mode in your tsconfig.json. This is a best practice for all TypeScript projects.

  1. ```ts
  2.   // tsconfig.json
  3.   {
  4.     // ...
  5.     "compilerOptions": {
  6.       // ...
  7.       "strict": true
  8.     }
  9.   }
  10. ```

From npm (Node/Bun)


  1. ```sh
  2. npm install zod       # npm
  3. yarn add zod          # yarn
  4. bun add zod           # bun
  5. pnpm add zod          # pnpm
  6. ```

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:

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

You can also specify a particular version:

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

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


Basic usage


Creating a simple string schema

  1. ```ts
  2. import { z } from "zod";

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

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

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

Creating an object schema

  1. ```ts
  2. import { z } from "zod";

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

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

  7. // extract the inferred type
  8. type User = z.infer<typeof User>;
  9. // { username: string }
  10. ```

Primitives


  1. ```ts
  2. import { z } from "zod";

  3. // primitive values
  4. z.string();
  5. z.number();
  6. z.bigint();
  7. z.boolean();
  8. z.date();
  9. z.symbol();

  10. // empty types
  11. z.undefined();
  12. z.null();
  13. z.void(); // accepts undefined

  14. // catch-all types
  15. // allows any value
  16. z.any();
  17. z.unknown();

  18. // never type
  19. // allows no values
  20. z.never();
  21. ```

Literals


  1. ```ts
  2. const tuna = z.literal("tuna");
  3. const twelve = z.literal(12);
  4. const twobig = z.literal(2n); // bigint literal
  5. const tru = z.literal(true);

  6. const terrificSymbol = Symbol("terrific");
  7. const terrific = z.literal(terrificSymbol);

  8. // retrieve literal value
  9. tuna.value; // "tuna"
  10. ```

Currently there is no support for Date literals in Zod. If you have a use case for this feature, please file an issue.


Strings


Zod includes a handful of string-specific validations.

  1. ```ts
  2. z.string().max(5);
  3. z.string().min(5);
  4. z.string().length(5);
  5. z.string().email();
  6. z.string().url();
  7. z.string().uuid();
  8. z.string().cuid();
  9. z.string().regex(regex);
  10. z.string().startsWith(string);
  11. z.string().endsWith(string);
  12. z.string().trim(); // trim whitespace
  13. z.string().datetime(); // defaults to UTC, see below for options
  14. ```

Check out validator.js for a bunch of other useful string validation functions that can be used in conjunction with Refinements.


You can customize some common error messages when creating a string schema.

  1. ```ts
  2. const name = z.string({
  3.   required_error: "Name is required",
  4.   invalid_type_error: "Name must be a string",
  5. });
  6. ```

When using validation methods, you can pass in an additional argument to provide a custom error message.

  1. ```ts
  2. z.string().min(5, { message: "Must be 5 or more characters long" });
  3. z.string().max(5, { message: "Must be 5 or fewer characters long" });
  4. z.string().length(5, { message: "Must be exactly 5 characters long" });
  5. z.string().email({ message: "Invalid email address" });
  6. z.string().url({ message: "Invalid url" });
  7. z.string().uuid({ message: "Invalid UUID" });
  8. z.string().startsWith("https://", { message: "Must provide secure URL" });
  9. z.string().endsWith(".com", { message: "Only .com domains allowed" });
  10. z.string().datetime({ message: "Invalid datetime string! Must be UTC." });
  11. ```

Datetime validation


The z.string().datetime() method defaults to UTC validation: no timezone offsets with arbitrary sub-second decimal precision.

  1. ```ts
  2. const datetime = z.string().datetime();

  3. datetime.parse("2020-01-01T00:00:00Z"); // pass
  4. datetime.parse("2020-01-01T00:00:00.123Z"); // pass
  5. datetime.parse("2020-01-01T00:00:00.123456Z"); // pass (arbitrary precision)
  6. datetime.parse("2020-01-01T00:00:00+02:00"); // fail (no offsets allowed)
  7. ```

Timezone offsets can be allowed by setting the offset option to true.

  1. ```ts
  2. const datetime = z.string().datetime({ offset: true });

  3. datetime.parse("2020-01-01T00:00:00+02:00"); // pass
  4. datetime.parse("2020-01-01T00:00:00.123+02:00"); // pass (millis optional)
  5. datetime.parse("2020-01-01T00:00:00Z"); // pass (Z still supported)
  6. ```

You can additionally constrain the allowable precision. By default, arbitrary sub-second precision is supported (but optional).

  1. ```ts
  2. const datetime = z.string().datetime({ precision: 3 });

  3. datetime.parse("2020-01-01T00:00:00.123Z"); // pass
  4. datetime.parse("2020-01-01T00:00:00Z"); // fail
  5. datetime.parse("2020-01-01T00:00:00.123456Z"); // fail
  6. ```

Numbers


You can customize certain error messages when creating a number schema.

  1. ```ts
  2. const age = z.number({
  3.   required_error: "Age is required",
  4.   invalid_type_error: "Age must be a number",
  5. });
  6. ```

Zod includes a handful of number-specific validations.

  1. ```ts
  2. z.number().gt(5);
  3. z.number().gte(5); // alias .min(5)
  4. z.number().lt(5);
  5. z.number().lte(5); // alias .max(5)

  6. z.number().int(); // value must be an integer

  7. z.number().positive(); //     > 0
  8. z.number().nonnegative(); //  >= 0
  9. z.number().negative(); //     < 0
  10. z.number().nonpositive(); //  <= 0

  11. z.number().multipleOf(5); // Evenly divisible by 5. Alias .step(5)

  12. z.number().finite(); // value must be finite, not Infinity or -Infinity
  13. ```

Optionally, you can pass in a second argument to provide a custom error message.

  1. ```ts
  2. z.number().lte(5, { message: "this👏is👏too👏big" });
  3. ```

NaNs


You can customize certain error messages when creating a nan schema.

  1. ```ts
  2. const isNaN = z.nan({
  3.   required_error: "isNaN is required",
  4.   invalid_type_error: "isNaN must be not a number",
  5. });
  6. ```

Booleans


You can customize certain error messages when creating a boolean schema.

  1. ```ts
  2. const isActive = z.boolean({
  3.   required_error: "isActive is required",
  4.   invalid_type_error: "isActive must be a boolean",
  5. });
  6. ```

Dates


Use z.date() to validate Date instances.

  1. ```ts
  2. z.date().safeParse(new Date()); // success: true
  3. z.date().safeParse("2022-01-12T00:00:00.000Z"); // success: false
  4. ```

You can customize certain error messages when creating a date schema.

  1. ```ts
  2. const myDateSchema = z.date({
  3.   required_error: "Please select a date and time",
  4.   invalid_type_error: "That's not a date!",
  5. });
  6. ```

Zod provides a handful of date-specific validations.

  1. ```ts
  2. z.date().min(new Date("1900-01-01"), { message: "Too old" });
  3. z.date().max(new Date(), { message: "Too young!" });
  4. ```

Supporting date strings

To write a schema that accepts either a Date or a date string, use [z.preprocess](#preprocess).

  1. ```ts
  2. const dateSchema = z.preprocess((arg) => {
  3.   if (typeof arg == "string" || arg instanceof Date) return new Date(arg);
  4. }, z.date());
  5. type DateSchema = z.infer<typeof dateSchema>;
  6. // type DateSchema = Date

  7. dateSchema.safeParse(new Date("1/12/22")); // success: true
  8. dateSchema.safeParse("2022-01-12T00:00:00.000Z"); // success: true
  9. ```

Zod enums


  1. ```ts
  2. const FishEnum = z.enum(["Salmon", "Tuna", "Trout"]);
  3. type FishEnum = z.infer<typeof FishEnum>;
  4. // 'Salmon' | 'Tuna' | 'Trout'
  5. ```

z.enum is a Zod-native way to declare a schema with a fixed set of allowable _string_ values. Pass the array of values directly into z.enum(). Alternatively, use as const to define your enum values as a tuple of strings. See the const assertion docs for details.

  1. ```ts
  2. const VALUES = ["Salmon", "Tuna", "Trout"] as const;
  3. const FishEnum = z.enum(VALUES);
  4. ```

This is not allowed, since Zod isn't able to infer the exact values of each element.

  1. ```ts
  2. const fish = ["Salmon", "Tuna", "Trout"];
  3. const FishEnum = z.enum(fish);
  4. ```

Autocompletion

To get autocompletion with a Zod enum, use the .enum property of your schema:

  1. ```ts
  2. FishEnum.enum.Salmon; // => autocompletes

  3. FishEnum.enum;
  4. /*
  5. => {
  6.   Salmon: "Salmon",
  7.   Tuna: "Tuna",
  8.   Trout: "Trout",
  9. }
  10. */
  11. ```

You can also retrieve the list of options as a tuple with the .options property:

  1. ```ts
  2. FishEnum.options; // ["Salmon", "Tuna", "Trout"]);
  3. ```

Native enums


Zod enums are the recommended approach to defining and validating enums. But if you need to validate against an enum from a third-party library (or you don't want to rewrite your existing enums) you can use z.nativeEnum().

Numeric enums

  1. ```ts
  2. enum Fruits {
  3.   Apple,
  4.   Banana,
  5. }

  6. const FruitEnum = z.nativeEnum(Fruits);
  7. type FruitEnum = z.infer<typeof FruitEnum>; // Fruits

  8. FruitEnum.parse(Fruits.Apple); // passes
  9. FruitEnum.parse(Fruits.Banana); // passes
  10. FruitEnum.parse(0); // passes
  11. FruitEnum.parse(1); // passes
  12. FruitEnum.parse(3); // fails
  13. ```

String enums

  1. ```ts
  2. enum Fruits {
  3.   Apple = "apple",
  4.   Banana = "banana",
  5.   Cantaloupe, // you can mix numerical and string enums
  6. }

  7. const FruitEnum = z.nativeEnum(Fruits);
  8. type FruitEnum = z.infer<typeof FruitEnum>; // Fruits

  9. FruitEnum.parse(Fruits.Apple); // passes
  10. FruitEnum.parse(Fruits.Cantaloupe); // passes
  11. FruitEnum.parse("apple"); // passes
  12. FruitEnum.parse("banana"); // passes
  13. FruitEnum.parse(0); // passes
  14. FruitEnum.parse("Cantaloupe"); // fails
  15. ```

Const enums

The .nativeEnum() function works for as const objects as well. ⚠️ as const required TypeScript 3.4+!

  1. ```ts
  2. const Fruits = {
  3.   Apple: "apple",
  4.   Banana: "banana",
  5.   Cantaloupe: 3,
  6. } as const;

  7. const FruitEnum = z.nativeEnum(Fruits);
  8. type FruitEnum = z.infer<typeof FruitEnum>; // "apple" | "banana" | 3

  9. FruitEnum.parse("apple"); // passes
  10. FruitEnum.parse("banana"); // passes
  11. FruitEnum.parse(3); // passes
  12. FruitEnum.parse("Cantaloupe"); // fails
  13. ```

You can access the underlying object with the .enum property:

  1. ```ts
  2. FruitEnum.enum.Apple; // "apple"
  3. ```

Optionals


You can make any schema optional with z.optional(). This wraps the schema in a ZodOptional instance and returns the result.

  1. ```ts
  2. const schema = z.optional(z.string());

  3. schema.parse(undefined); // => returns undefined
  4. type A = z.infer<typeof schema>; // string | undefined
  5. ```

For convenience, you can also call the .optional() method on an existing schema.

  1. ```ts
  2. const user = z.object({
  3.   username: z.string().optional(),
  4. });
  5. type C = z.infer<typeof user>; // { username?: string | undefined };
  6. ```

You can extract the wrapped schema from a ZodOptional instance with .unwrap().

  1. ```ts
  2. const stringSchema = z.string();
  3. const optionalString = stringSchema.optional();
  4. optionalString.unwrap() === stringSchema; // true
  5. ```

Nullables


Similarly, you can create nullable types with z.nullable().

  1. ```ts
  2. const nullableString = z.nullable(z.string());
  3. nullableString.parse("asdf"); // => "asdf"
  4. nullableString.parse(null); // => null
  5. ```

Or use the .nullable() method.

  1. ```ts
  2. const E = z.string().nullable(); // equivalent to nullableString
  3. type E = z.infer<typeof E>; // string | null
  4. ```

Extract the inner schema with .unwrap().

  1. ```ts
  2. const stringSchema = z.string();
  3. const nullableString = stringSchema.nullable();
  4. nullableString.unwrap() === stringSchema; // true
  5. ```

Objects


  1. ```ts
  2. // all properties are required by default
  3. const Dog = z.object({
  4.   name: z.string(),
  5.   age: z.number(),
  6. });

  7. // extract the inferred type like this
  8. type Dog = z.infer<typeof Dog>;

  9. // equivalent to:
  10. type Dog = {
  11.   name: string;
  12.   age: number;
  13. };
  14. ```

.shape


Use .shape to access the schemas for a particular key.

  1. ```ts
  2. Dog.shape.name; // => string schema
  3. Dog.shape.age; // => number schema
  4. ```

.keyof


Use .keyof to create a ZodEnum schema from the keys of an object schema.

  1. ```ts
  2. const keySchema = Dog.keyof();
  3. keySchema; // ZodEnum<["name", "age"]>
  4. ```

.extend


You can add additional fields to an object schema with the .extend method.

  1. ```ts
  2. const DogWithBreed = Dog.extend({
  3.   breed: z.string(),
  4. });
  5. ```

You can use .extend to overwrite fields! Be careful with this power!

.merge


Equivalent to A.extend(B.shape).

  1. ```ts
  2. const BaseTeacher = z.object({ students: z.array(z.string()) });
  3. const HasID = z.object({ id: z.string() });

  4. const Teacher = BaseTeacher.merge(HasID);
  5. type Teacher = z.infer<typeof Teacher>; // => { students: string[], id: string }
  6. ```

If the two schemas share keys, the properties of B overrides the property of A. The returned schema also inherits the "unknownKeys" policy (strip/strict/passthrough) and the catchall schema of B.


.pick/.omit


Inspired by TypeScript's built-in Pick and Omit utility types, all Zod object schemas have .pick and .omit methods that return a modified version. Consider this Recipe schema:

  1. ```ts
  2. const Recipe = z.object({
  3.   id: z.string(),
  4.   name: z.string(),
  5.   ingredients: z.array(z.string()),
  6. });
  7. ```

To only keep certain keys, use .pick .

  1. ```ts
  2. const JustTheName = Recipe.pick({ name: true });
  3. type JustTheName = z.infer<typeof JustTheName>;
  4. // => { name: string }
  5. ```

To remove certain keys, use .omit .

  1. ```ts
  2. const NoIDRecipe = Recipe.omit({ id: true });

  3. type NoIDRecipe = z.infer<typeof NoIDRecipe>;
  4. // => { name: string, ingredients: string[] }
  5. ```

.partial


Inspired by the built-in TypeScript utility type Partial, the.partial method makes all properties optional.

Starting from this object:

  1. ```ts
  2. const user = z.object({
  3.   email: z.string()
  4.   username: z.string(),
  5. });
  6. // { email: string; username: string }
  7. ```

We can create a partial version:

  1. ```ts
  2. const partialUser = user.partial();
  3. // { email?: string | undefined; username?: string | undefined }
  4. ```

You can also specify which properties to make optional:

  1. ```ts
  2. const optionalEmail = user.partial({
  3.   email: true,
  4. });
  5. /*
  6. {
  7.   email?: string | undefined;
  8.   username: string
  9. }
  10. */
  11. ```

.deepPartial


The .partial method is shallow — it only applies one level deep. There is also a "deep" version:

  1. ```ts
  2. const user = z.object({
  3.   username: z.string(),
  4.   location: z.object({
  5.     latitude: z.number(),
  6.     longitude: z.number(),
  7.   }),
  8.   strings: z.array(z.object({ value: z.string() })),
  9. });

  10. const deepPartialUser = user.deepPartial();

  11. /*
  12. {
  13.   username?: string | undefined,
  14.   location?: {
  15.     latitude?: number | undefined;
  16.     longitude?: number | undefined;
  17.   } | undefined,
  18.   strings?: { value?: string}[]
  19. }
  20. */
  21. ```

Important limitation: deep partials only work as expected in hierarchies of objects, arrays, and tuples.


.required


Contrary to the .partial method, the .required method makes all properties required.

Starting from this object:

  1. ```ts
  2. const user = z.object({
  3.   email: z.string()
  4.   username: z.string(),
  5. }).partial();
  6. // { email?: string | undefined; username?: string | undefined }
  7. ```

We can create a required version:

  1. ```ts
  2. const requiredUser = user.required();
  3. // { email: string; username: string }
  4. ```

You can also specify which properties to make required:

  1. ```ts
  2. const requiredEmail = user.required({
  3.   email: true,
  4. });
  5. /*
  6. {
  7.   email: string;
  8.   username?: string | undefined;
  9. }
  10. */
  11. ```

.passthrough


By default Zod object schemas strip out unrecognized keys during parsing.

  1. ```ts
  2. const person = z.object({
  3.   name: z.string(),
  4. });

  5. person.parse({
  6.   name: "bob dylan",
  7.   extraKey: 61,
  8. });
  9. // => { name: "bob dylan" }
  10. // extraKey has been stripped
  11. ```

Instead, if you want to pass through unknown keys, use .passthrough() .

  1. ```ts
  2. person.passthrough().parse({
  3.   name: "bob dylan",
  4.   extraKey: 61,
  5. });
  6. // => { name: "bob dylan", extraKey: 61 }
  7. ```

.strict


By default Zod object schemas strip out unrecognized keys during parsing. You can _disallow_ unknown keys with .strict() . If there are any unknown keys in the input, Zod will throw an error.

  1. ```ts
  2. const person = z
  3.   .object({
  4.     name: z.string(),
  5.   })
  6.   .strict();

  7. person.parse({
  8.   name: "bob dylan",
  9.   extraKey: 61,
  10. });
  11. // => throws ZodError
  12. ```

.strip


You can use the .strip method to reset an object schema to the default behavior (stripping unrecognized keys).

.catchall


You can pass a "catchall" schema into an object schema. All unknown keys will be validated against it.

  1. ```ts
  2. const person = z
  3.   .object({
  4.     name: z.string(),
  5.   })
  6.   .catchall(z.number());

  7. person.parse({
  8.   name: "bob dylan",
  9.   validExtraKey: 61, // works fine
  10. });

  11. person.parse({
  12.   name: "bob dylan",
  13.   validExtraKey: false, // fails
  14. });
  15. // => throws ZodError
  16. ```

Using .catchall() obviates .passthrough() , .strip() , or .strict(). All keys are now considered "known".

Arrays


  1. ```ts
  2. const stringArray = z.array(z.string());

  3. // equivalent
  4. const stringArray = z.string().array();
  5. ```

Be careful with the .array() method. It returns a new ZodArray instance. This means the _order_ in which you call methods matters. For instance:

  1. ```ts
  2. z.string().optional().array(); // (string | undefined)[]
  3. z.string().array().optional(); // string[] | undefined
  4. ```

.element


Use .element to access the schema for an element of the array.

  1. ```ts
  2. stringArray.element; // => string schema
  3. ```

.nonempty


If you want to ensure that an array contains at least one element, use .nonempty().

  1. ```ts
  2. const nonEmptyStrings = z.string().array().nonempty();
  3. // the inferred type is now
  4. // [string, ...string[]]

  5. nonEmptyStrings.parse([]); // throws: "Array cannot be empty"
  6. nonEmptyStrings.parse(["Ariana Grande"]); // passes
  7. ```

You can optionally specify a custom error message:

  1. ```ts
  2. // optional custom error message
  3. const nonEmptyStrings = z.string().array().nonempty({
  4.   message: "Can't be empty!",
  5. });
  6. ```

.min/.max/.length


  1. ```ts
  2. z.string().array().min(5); // must contain 5 or more items
  3. z.string().array().max(5); // must contain 5 or fewer items
  4. z.string().array().length(5); // must contain 5 items exactly
  5. ```

Unlike .nonempty() these methods do not change the inferred type.

Tuples


Unlike arrays, tuples have a fixed number of elements and each element can have a different type.

  1. ```ts
  2. const athleteSchema = z.tuple([
  3.   z.string(), // name
  4.   z.number(), // jersey number
  5.   z.object({
  6.     pointsScored: z.number(),
  7.   }), // statistics
  8. ]);

  9. type Athlete = z.infer<typeof athleteSchema>;
  10. // type Athlete = [string, number, { pointsScored: number }]
  11. ```

A variadic ("rest") argument can be added with the .rest method.

  1. ```ts
  2. const variadicTuple = z.tuple([z.string()]).rest(z.number());
  3. const result = variadicTuple.parse(["hello", 1, 2, 3]);
  4. // => [string, ...number[]];
  5. ```

Unions


Zod includes a built-in z.union method for composing "OR" types.

  1. ```ts
  2. const stringOrNumber = z.union([z.string(), z.number()]);

  3. stringOrNumber.parse("foo"); // passes
  4. stringOrNumber.parse(14); // passes
  5. ```

Zod will test the input against each of the "options" in order and return the first value that validates successfully.

For convenience, you can also use the .or method:

  1. ```ts
  2. const stringOrNumber = z.string().or(z.number());
  3. ```

Discriminated unions


A discriminated union is a union of object schemas that all share a particular key.

  1. ```ts
  2. type MyUnion =
  3.   | { status: "success"; data: string }
  4.   | { status: "failed"; error: Error };
  5. ```

Such unions can be represented with the z.discriminatedUnion method. This enables faster evaluation, because Zod can check the _discriminator key_ (status in the example above) ot determine which schema should be used to parse the input. This makes parsing more efficient and lets Zod provide report friendlier errors.

With the basic union method the input is tested against each of the provided "options", and in the case of invalidity, issues for all the "options" are shown in the zod error. On the other hand, the discriminated union allows for selecting just one of the "options", testing against it, and showing only the issues related to this "option".

  1. ```ts
  2. const myUnion = z.discriminatedUnion("status", [
  3.   z.object({ status: z.literal("success"), data: z.string() }),
  4.   z.object({ status: z.literal("failed"), error: z.instanceof(Error) }),
  5. ]);

  6. myUnion.parse({ type: "success", data: "yippie ki yay" });
  7. ```

Records


Record schemas are used to validate types such as { [k: string]: number }.

If you want to validate the _values_ of an object against some schema but don't care about the keys, use z.record(valueType):

  1. ```ts
  2. const NumberCache = z.record(z.number());

  3. type NumberCache = z.infer<typeof NumberCache>;
  4. // => { [k: string]: number }
  5. ```

This is particularly useful for storing or caching items by ID.

  1. ```ts
  2. const userStore: UserStore = {};

  3. userStore["77d2586b-9e8e-4ecf-8b21-ea7e0530eadd"] = {
  4.   name: "Carlotta",
  5. }; // passes

  6. userStore["77d2586b-9e8e-4ecf-8b21-ea7e0530eadd"] = {
  7.   whatever: "Ice cream sundae",
  8. }; // TypeError
  9. ```

Record key type


If you want to validate both the keys and the values, use
z.record(keyType, valueType):

  1. ```ts
  2. const NoEmptyKeysSchema = z.record(z.string().min(1), z.number());
  3. NoEmptyKeysSchema.parse({ count: 1 }); // => { 'count': 1 }
  4. NoEmptyKeysSchema.parse({ "": 1 }); // fails
  5. ```

_(Notice how when passing two arguments, valueType is the second argument)_

A note on numerical keys

While `z.record(keyType, valueType)` is able to accept numerical key types and TypeScript's built-in Record type is `Record`, it's hard to represent the TypeScript type `Record` in Zod.

As it turns out, TypeScript's behavior surrounding [k: number] is a little unintuitive:

  1. ```ts
  2. const testMap: { [k: number]: string } = {
  3.   1: "one",
  4. };

  5. for (const key in testMap) {
  6.   console.log(`${key}: ${typeof key}`);
  7. }
  8. // prints: `1: string`
  9. ```

As you can see, JavaScript automatically casts all object keys to strings under the hood. Since Zod is trying to bridge the gap between static and runtime types, it doesn't make sense to provide a way of creating a record schema with numerical keys, since there's no such thing as a numerical key in runtime JavaScript.

Maps


  1. ```ts
  2. const stringNumberMap = z.map(z.string(), z.number());

  3. type StringNumberMap = z.infer<typeof stringNumberMap>;
  4. // type StringNumberMap = Map
  5. ```

Sets


  1. ```ts
  2. const numberSet = z.set(z.number());
  3. type NumberSet = z.infer<typeof numberSet>;
  4. // type NumberSet = Set
  5. ```

Set schemas can be further contrainted with the following utility methods.

  1. ```ts
  2. z.set(z.string()).nonempty(); // must contain at least one item
  3. z.set(z.string()).min(5); // must contain 5 or more items
  4. z.set(z.string()).max(5); // must contain 5 or fewer items
  5. z.set(z.string()).size(5); // must contain 5 items exactly
  6. ```

Intersections


Intersections are useful for creating "logical AND" types. This is useful for intersecting two object types.

  1. ```ts
  2. const Person = z.object({
  3.   name: z.string(),
  4. });

  5. const Employee = z.object({
  6.   role: z.string(),
  7. });

  8. const EmployedPerson = z.intersection(Person, Employee);

  9. // equivalent to:
  10. const EmployedPerson = Person.and(Employee);
  11. ```

Though in many cases, it is recommended to use A.merge(B) to merge two objects. The .merge method returns a new ZodObject instance, whereas A.and(B) returns a less useful ZodIntersection instance that lacks common object methods like pick and omit.

  1. ```ts
  2. const a = z.union([z.number(), z.string()]);
  3. const b = z.union([z.number(), z.boolean()]);
  4. const c = z.intersection(a, b);

  5. type c = z.infer<typeof c>; // => number
  6. ```



<!--

  1. ``` ts
  2. const A = z.object({
  3.   a: z.string(),
  4. });

  5. const B = z.object({
  6.   b: z.string(),
  7. });

  8. const AB = z.intersection(A, B);

  9. type Teacher = z.infer<typeof Teacher>;
  10. // { id:string; name:string };
  11. ```  -->

Recursive types


You can define a recursive schema in Zod, but because of a limitation of TypeScript, their type can't be statically inferred. Instead you'll need to define the type definition manually, and provide it to Zod as a "type hint".

  1. ```ts
  2. interface Category {
  3.   name: string;
  4.   subcategories: Category[];
  5. }

  6. // cast to z.ZodType
  7. const Category: z.ZodType<Category> = z.lazy(() =>
  8.   z.object({
  9.     name: z.string(),
  10.     subcategories: z.array(Category),
  11.   })
  12. );

  13. Category.parse({
  14.   name: "People",
  15.   subcategories: [
  16.     {
  17.       name: "Politicians",
  18.       subcategories: [{ name: "Presidents", subcategories: [] }],
  19.     },
  20.   ],
  21. }); // passes
  22. ```

Unfortunately this code is a bit duplicative, since you're declaring the types twice: once in the interface and again in the Zod definition.

<!-- If your schema has lots of primitive fields, there's a way of reducing the amount of duplication:

  1. ```ts
  2. // define all the non-recursive stuff here
  3. const BaseCategory = z.object({
  4.   name: z.string(),
  5.   tags: z.array(z.string()),
  6.   itemCount: z.number(),
  7. });

  8. // create an interface that extends the base schema
  9. interface Category extends z.infer<typeof BaseCategory> {
  10.   subcategories: Category[];
  11. }

  12. // merge the base schema with
  13. // a new Zod schema containing relations
  14. const Category: z.ZodType<Category> = BaseCategory.merge(
  15.   z.object({
  16.     subcategories: z.lazy(() => z.array(Category)),
  17.   })
  18. );
  19. ``` -->

JSON type


If you want to validate any JSON value, you can use the snippet below.

  1. ```ts
  2. const literalSchema = z.union([z.string(), z.number(), z.boolean(), z.null()]);
  3. type Literal = z.infer<typeof literalSchema>;
  4. type Json = Literal | { [key: string]: Json } | Json[];
  5. const jsonSchema: z.ZodType<Json> = z.lazy(() =>
  6.   z.union([literalSchema, z.array(jsonSchema), z.record(jsonSchema)])
  7. );

  8. jsonSchema.parse(data);
  9. ```

Thanks to ggoodman for suggesting this.

Cyclical objects


Despite supporting recursive schemas, passing cyclical data into Zod will cause an infinite loop.

Promises


  1. ```ts
  2. const numberPromise = z.promise(z.number());
  3. ```

"Parsing" works a little differently with promise schemas. Validation happens in two parts:

1. Zod synchronously checks that the input is an instance of Promise (i.e. an object with .then and .catch methods.).
2. Zod uses .then to attach an additional validation step onto the existing Promise. You'll have to use .catch on the returned Promise to handle validation failures.

  1. ```ts
  2. numberPromise.parse("tuna");
  3. // ZodError: Non-Promise type: string

  4. numberPromise.parse(Promise.resolve("tuna"));
  5. // => Promise

  6. const test = async () => {
  7.   await numberPromise.parse(Promise.resolve("tuna"));
  8.   // ZodError: Non-number type: string

  9.   await numberPromise.parse(Promise.resolve(3.14));
  10.   // => 3.14
  11. };
  12. ```

<!-- #### Non-native promise implementations

When "parsing" a promise, Zod checks that the passed value is an object with .then and .catch methods — that's it. So you should be able to pass non-native Promises (Bluebird, etc) into z.promise(...).parse with no trouble. One gotcha: the return type of the parse function will be a _native_ Promise , so if you have downstream logic that uses non-standard Promise methods, this won't work. -->

Instanceof


You can use z.instanceof to check that the input is an instance of a class. This is useful to validate inputs against classes that are exported from third-party libraries.

  1. ```ts
  2. class Test {
  3.   name: string;
  4. }

  5. const TestSchema = z.instanceof(Test);

  6. const blob: any = "whatever";
  7. TestSchema.parse(new Test()); // passes
  8. TestSchema.parse("blob"); // throws
  9. ```

Function schemas


Zod also lets you define "function schemas". This makes it easy to validate the inputs and outputs of a function without intermixing your validation code and "business logic".

You can create a function schema with z.function(args, returnType) .

  1. ```ts
  2. const myFunction = z.function();

  3. type myFunction = z.infer<typeof myFunction>;
  4. // => ()=>unknown
  5. ```

Define inputs and outputs.

  1. ```ts
  2. const myFunction = z
  3.   .function()
  4.   .args(z.string(), z.number()) // accepts an arbitrary number of arguments
  5.   .returns(z.boolean());
  6. type myFunction = z.infer<typeof myFunction>;
  7. // => (arg0: string, arg1: number)=>boolean
  8. ```

<!--

  1. ``` ts
  2. const args = z.tuple([z.string()]);

  3. const returnType = z.number();

  4. const myFunction = z.function(args, returnType);
  5. type myFunction = z.infer<typeof myFunction>;
  6. // => (arg0: string)=>number
  7. ``` -->

Function schemas have an .implement() method which accepts a function and returns a new function that automatically validates its inputs and outputs.

  1. ```ts
  2. const trimmedLength = z
  3.   .function()
  4.   .args(z.string()) // accepts an arbitrary number of arguments
  5.   .returns(z.number())
  6.   .implement((x) => {
  7.     // TypeScript knows x is a string!
  8.     return x.trim().length;
  9.   });

  10. trimmedLength("sandwich"); // => 8
  11. trimmedLength(" asdf "); // => 4
  12. ```

If you only care about validating inputs, just don't call the .returns() method. The output type will be inferred from the implementation.

You can use the special z.void() option if your function doesn't return anything. This will let Zod properly infer the type of void-returning functions. (Void-returning functions actually return undefined.)


  1. ```ts
  2. const myFunction = z
  3.   .function()
  4.   .args(z.string())
  5.   .implement((arg) => {
  6.     return [arg.length]; //
  7.   });
  8. myFunction; // (arg: string)=>number[]
  9. ```

Extract the input and output schemas from a function schema.

  1. ```ts
  2. myFunction.parameters();
  3. // => ZodTuple<[ZodString, ZodNumber]>

  4. myFunction.returnType();
  5. // => ZodBoolean
  6. ```

<!-- z.function() accepts two arguments:

args: ZodTuple The first argument is a tuple (created with z.tuple([...]) and defines the schema of the arguments to your function. If the function doesn't accept arguments, you can pass an empty tuple (z.tuple([])).
returnType: any Zod schema The second argument is the function's return type. This can be any Zod schema. -->

Preprocess


Typically Zod operates under a "parse then transform" paradigm. Zod validates the input first, then passes it through a chain of transformation functions. (For more information about transforms, read the .transform docs.)

But sometimes you want to apply some transform to the input _before_ parsing happens. A common use case: type coercion. Zod enables this with the z.preprocess().

  1. ```ts
  2. const castToString = z.preprocess((val) => String(val), z.string());
  3. ```

This returns a ZodEffects instance. ZodEffects is a wrapper class that contains all logic pertaining to preprocessing, refinements, and transforms.

Schema methods


All Zod schemas contain certain methods.

.parse


.parse(data: unknown): T

Given any Zod schema, you can call its .parse method to check data is valid. If it is, a value is returned with full type information! Otherwise, an error is thrown.

IMPORTANT: The value returned by .parse is a _deep clone_ of the variable you passed in.


  1. ```ts
  2. const stringSchema = z.string();
  3. stringSchema.parse("fish"); // => returns "fish"
  4. stringSchema.parse(12); // throws Error('Non-string type: number');
  5. ```

.parseAsync


`.parseAsync(data:unknown): Promise`

If you use asynchronous refinements or transforms (more on those later), you'll need to use.parseAsync

  1. ```ts
  2. const stringSchema1 = z.string().refine(async (val) => val.length < 20);
  3. const value1 = await stringSchema.parseAsync("hello"); // => hello

  4. const stringSchema2 = z.string().refine(async (val) => val.length > 20);
  5. const value2 = await stringSchema.parseAsync("hello"); // => throws
  6. ```

.safeParse


.safeParse(data:unknown): { success: true; data: T; } | { success: false; error: ZodError; }

If you don't want Zod to throw errors when validation fails, use .safeParse. This method returns an object containing either the successfully parsed data or a ZodError instance containing detailed information about the validation problems.

  1. ```ts
  2. stringSchema.safeParse(12);
  3. // => { success: false; error: ZodError }

  4. stringSchema.safeParse("billie");
  5. // => { success: true; data: 'billie' }
  6. ```

The result is a _discriminated union_ so you can handle errors very conveniently:

  1. ```ts
  2. const result = stringSchema.safeParse("billie");
  3. if (!result.success) {
  4.   // handle error then return
  5.   result.error;
  6. } else {
  7.   // do something
  8.   result.data;
  9. }
  10. ```

.safeParseAsync


Alias: .spa


An asynchronous version of safeParse.

  1. ```ts
  2. await stringSchema.safeParseAsync("billie");
  3. ```

For convenience, this has been aliased to .spa:

  1. ```ts
  2. await stringSchema.spa("billie");
  3. ```

.refine


.refine(validator: (data:T)=>any, params?: RefineParams)

Zod lets you provide custom validation logic via _refinements_. (For advanced features like creating multiple issues and customizing error codes, see [.superRefine](#superrefine).)

Zod was designed to mirror TypeScript as closely as possible. But there are many so-called "refinement types" you may wish to check for that can't be represented in TypeScript's type system. For instance: checking that a number is an integer or that a string is a valid email address.

For example, you can define a custom validation check on _any_ Zod schema with .refine :

  1. ```ts
  2. const myString = z.string().refine((val) => val.length <= 255, {
  3.   message: "String can't be more than 255 characters",
  4. });
  5. ```

⚠️ Refinement functions should not throw. Instead they should return a falsy value to signal failure.


Arguments


As you can see, .refine takes two arguments.

1. The first is the validation function. This function takes one input (of type T — the inferred type of the schema) and returns any. Any truthy value will pass validation. (Prior to zod@1.6.2 the validation function had to return a boolean.)
2. The second argument accepts some options. You can use this to customize certain error-handling behavior:

  1. ```ts
  2. type RefineParams = {
  3.   // override error message
  4.   message?: string;

  5.   // appended to error path
  6.   path?: (string | number)[];

  7.   // params object you can use to customize message
  8.   // in error map
  9.   params?: object;
  10. };
  11. ```

For advanced cases, the second argument can also be a function that returns RefineParams/

  1. ```ts
  2. z.string().refine(
  3.   (val) => val.length > 10,
  4.   (val) => ({ message: `${val} is not more than 10 characters` })
  5. );
  6. ```

Customize error path


  1. ```ts
  2. const passwordForm = z
  3.   .object({
  4.     password: z.string(),
  5.     confirm: z.string(),
  6.   })
  7.   .refine((data) => data.password === data.confirm, {
  8.     message: "Passwords don't match",
  9.     path: ["confirm"], // path of error
  10.   })
  11.   .parse({ password: "asdf", confirm: "qwer" });
  12. ```

Because you provided a path parameter, the resulting error will be:

  1. ```ts
  2. ZodError {
  3.   issues: [{
  4.     "code": "custom",
  5.     "path": [ "confirm" ],
  6.     "message": "Passwords don't match"
  7.   }]
  8. }
  9. ```

Asynchronous refinements


Refinements can also be async:

  1. ```ts
  2. const userId = z.string().refine(async (id) => {
  3.   // verify that ID exists in database
  4.   return true;
  5. });
  6. ```

⚠️ If you use async refinements, you must use the .parseAsync method to parse data! Otherwise Zod will throw an error.


Relationship to transforms


Transforms and refinements can be interleaved:

  1. ```ts
  2. z.string()
  3.   .transform((val) => val.length)
  4.   .refine((val) => val > 25);
  5. ```

<!-- Note that the path is set to ["confirm"] , so you can easily display this error underneath the "Confirm password" textbox.


  1. ```ts
  2. const allForms = z.object({ passwordForm }).parse({
  3.   passwordForm: {
  4.     password: "asdf",
  5.     confirm: "qwer",
  6.   },
  7. });
  8. ```

would result in

  1. ```

  2. ZodError {
  3.   issues: [{
  4.     "code": "custom",
  5.     "path": [ "passwordForm", "confirm" ],
  6.     "message": "Passwords don't match"
  7.   }]
  8. }
  9. ``` -->

.superRefine


The .refine method is actually syntactic sugar atop a more versatile (and verbose) method called superRefine. Here's an example:

  1. ```ts
  2. const Strings = z.array(z.string()).superRefine((val, ctx) => {
  3.   if (val.length > 3) {
  4.     ctx.addIssue({
  5.       code: z.ZodIssueCode.too_big,
  6.       maximum: 3,
  7.       type: "array",
  8.       inclusive: true,
  9.       message: "Too many items 😡",
  10.     });
  11.   }

  12.   if (val.length !== new Set(val).size) {
  13.     ctx.addIssue({
  14.       code: z.ZodIssueCode.custom,
  15.       message: `No duplicates allowed.`,
  16.     });
  17.   }
  18. });
  19. ```

You can add as many issues as you like. If ctx.addIssue is _not_ called during the execution of the function, validation passes.

Normally refinements always create issues with a ZodIssueCode.custom error code, but with superRefine you can create any issue of any code. Each issue code is described in detail in the Error Handling guide: ERROR_HANDLING.md.

Abort early


By default, parsing will continue even after a refinement check fails. For instance, if you chain together multiple refinements, they will all be executed. However, it may be desirable to _abort early_ to prevent later refinements from being executed. To achieve this, pass the fatal flag to ctx.addIssue and return z.NEVER.

  1. ```ts
  2. const schema = z.number().superRefine((val, ctx) => {
  3.   if (val < 10) {
  4.     ctx.addIssue({
  5.       code: z.ZodIssueCode.custom,
  6.       message: "should be >= 10",
  7.       fatal: true,
  8.     });

  9.     return z.NEVER;
  10.   }

  11.   if (val !== 12) {
  12.     ctx.addIssue({
  13.       code: z.ZodIssueCode.custom,
  14.       message: "should be twelve",
  15.     });
  16.   }
  17. });
  18. ```

.transform


To transform data after parsing, use the transform method.

  1. ```ts
  2. const stringToNumber = z.string().transform((val) => val.length);
  3. stringToNumber.parse("string"); // => 6
  4. ```

Chaining order


Note that stringToNumber above is an instance of the ZodEffects subclass. It is NOT an instance of ZodString. If you want to use the built-in methods of ZodString (e.g. .email()) you must apply those methods _before_ any transforms.

  1. ```ts
  2. const emailToDomain = z
  3.   .string()
  4.   .email()
  5.   .transform((val) => val.split("@")[1]);

  6. emailToDomain.parse("colinhacks@example.com"); // => example.com
  7. ```

Validating during transform


The .transform method can simultaneously validate and transform the value. This is often simpler and less duplicative than chaining refine and validate.

As with .superRefine, the transform function receives a ctx object with a addIssue method that can be used to register validation issues.

  1. ```ts
  2. const Strings = z.string().transform((val, ctx) => {
  3.   const parsed = parseInt(val);
  4.   if (isNaN(parsed)) {
  5.     ctx.addIssue({
  6.       code: z.ZodIssueCode.custom,
  7.       message: "Not a number",
  8.     });

  9.     // This is a special symbol you can use to
  10.     // return early from the transform function.
  11.     // It has type `never` so it does not affect the
  12.     // inferred return type.
  13.     return z.NEVER;
  14.   }
  15.   return parsed;
  16. });
  17. ```

Relationship to refinements


Transforms and refinements can be interleaved. These will be executed in the order they are declared.

  1. ```ts
  2. z.string()
  3.   .transform((val) => val.toUpperCase())
  4.   .refine((val) => val.length > 15)
  5.   .transform((val) => `Hello ${val}`)
  6.   .refine((val) => val.indexOf("!") === -1);
  7. ```

Async transforms


Transforms can also be async.

  1. ```ts
  2. const IdToUser = z
  3.   .string()
  4.   .uuid()
  5.   .transform(async (id) => {
  6.     return await getUserById(id);
  7.   });
  8. ```

⚠️ If your schema contains asynchronous transforms, you must use .parseAsync() or .safeParseAsync() to parse data. Otherwise Zod will throw an error.


.default


You can use transforms to implement the concept of "default values" in Zod.

  1. ```ts
  2. const stringWithDefault = z.string().default("tuna");

  3. stringWithDefault.parse(undefined); // => "tuna"
  4. ```

Optionally, you can pass a function into .default that will be re-executed whenever a default value needs to be generated:

  1. ```ts
  2. const numberWithRandomDefault = z.number().default(Math.random);

  3. numberWithRandomDefault.parse(undefined); // => 0.4413456736055323
  4. numberWithRandomDefault.parse(undefined); // => 0.1871840107401901
  5. numberWithRandomDefault.parse(undefined); // => 0.7223408162401552
  6. ```

Conceptually, this is how Zod processes default values:

1. If the input is undefined, the default value is returned
2. Otherwise, the data is parsed using the base schema

.catch


Use .catch() to provide a "catch value" to be returned in the event of a parsing error.

  1. ```ts
  2. const numberWithCatch = z.number().catch(42);

  3. numberWithCatch.parse(5); // => 5
  4. numberWithCatch.parse("tuna"); // => 42
  5. ```

Optionally, you can pass a function into .catch that will be re-executed whenever a default value needs to be generated:

  1. ```ts
  2. const numberWithRandomCatch = z.number().catch(Math.random);

  3. numberWithRandomDefault.parse("sup"); // => 0.4413456736055323
  4. numberWithRandomDefault.parse("sup"); // => 0.1871840107401901
  5. numberWithRandomDefault.parse("sup"); // => 0.7223408162401552
  6. ```

Conceptually, this is how Zod processes "catch values":

1. The data is parsed using the base schema
2. If the parsing fails, the "catch value" is returned

.optional


A convenience method that returns an optional version of a schema.

  1. ```ts
  2. const optionalString = z.string().optional(); // string | undefined

  3. // equivalent to
  4. z.optional(z.string());
  5. ```

.nullable


A convenience method that returns a nullable version of a schema.

  1. ```ts
  2. const nullableString = z.string().nullable(); // string | null

  3. // equivalent to
  4. z.nullable(z.string());
  5. ```

.nullish


A convenience method that returns a "nullish" version of a schema. Nullish schemas will accept both undefined and null. Read more about the concept of "nullish" in the TypeScript 3.7 release notes.

  1. ```ts
  2. const nullishString = z.string().nullish(); // string | null | undefined

  3. // equivalent to
  4. z.string().optional().nullable();
  5. ```

.array


A convenience method that returns an array schema for the given type:

  1. ```ts
  2. const nullableString = z.string().array(); // string[]

  3. // equivalent to
  4. z.array(z.string());
  5. ```

.promise


A convenience method for promise types:

  1. ```ts
  2. const stringPromise = z.string().promise(); // Promise

  3. // equivalent to
  4. z.promise(z.string());
  5. ```

.or


A convenience method for union types.

  1. ```ts
  2. z.string().or(z.number()); // string | number

  3. // equivalent to
  4. z.union([z.string(), z.number()]);
  5. ```

.and


A convenience method for creating intersection types.

  1. ```ts
  2. z.object({ name: z.string() }).and(z.object({ age: z.number() })); // { name: string } & { age: number }

  3. // equivalent to
  4. z.intersection(z.object({ name: z.string() }), z.object({ age: z.number() }));
  5. ```

.brand


`.brand() => ZodBranded`

TypeScript's type system is structural, which means that any two types that are structurally equivalent are considered the same.

  1. ```ts
  2. type Cat = { name: string };
  3. type Dog = { name: string };

  4. const petCat = (cat: Cat) => {};
  5. const fido: Dog = { name: "fido" };
  6. petCat(fido); // works fine
  7. ```

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_).

  1. ```ts
  2. const Cat = z.object({ name: z.string() }).brand<"Cat">();
  3. type Cat = z.infer<typeof Cat>;

  4. const petCat = (cat: Cat) => {};

  5. // this works
  6. const simba = Cat.parse({ name: "simba" });
  7. petCat(simba);

  8. // this doesn't
  9. petCat({ name: "fido" });
  10. ```

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.

  1. ```ts
  2. const Cat = z.object({ name: z.string() }).brand<"Cat">();
  3. type Cat = z.infer<typeof Cat>;
  4. // {name: string} & {[symbol]: "Cat"}
  5. ```

Note that branded types do not affect the runtime result of .parse. It is a static-only construct.

Guides and concepts


Type inference


You can extract the TypeScript type of any schema with `z.infer` .

  1. ```ts
  2. const A = z.string();
  3. type A = z.infer<typeof A>; // string

  4. const u: A = 12; // TypeError
  5. const u: A = "asdf"; // compiles
  6. ```

What about transforms?

In reality each Zod schema internally tracks two types: an input and an output. For most schemas (e.g. z.string()) these two are the same. But once you add transforms into the mix, these two values can diverge. For instance z.string().transform(val => val.length) has an input of string and an output of number.

You can separately extract the input and output ty