{"name":"zod","version":"3.24.0-canary.20240701T200529","author":{"name":"Colin McDonnell","email":"colin@colinhacks.com"},"repository":{"type":"git","url":"git+https://github.com/colinhacks/zod.git"},"main":"./lib/index.js","module":"./lib/index.mjs","devDependencies":{"@babel/core":"^7.22.5","@babel/preset-env":"^7.22.5","@babel/preset-typescript":"^7.22.5","@jest/globals":"^29.4.3","@rollup/plugin-typescript":"^8.2.0","@swc/core":"^1.3.66","@swc/jest":"^0.2.26","@types/benchmark":"^2.1.0","@types/jest":"^29.2.2","@types/node":"14","@typescript-eslint/eslint-plugin":"^5.15.0","@typescript-eslint/parser":"^5.15.0","babel-jest":"^29.5.0","benchmark":"^2.1.4","dependency-cruiser":"^9.19.0","eslint":"^8.11.0","eslint-config-prettier":"^8.5.0","eslint-plugin-ban":"^1.6.0","eslint-plugin-import":"^2.25.4","eslint-plugin-simple-import-sort":"^7.0.0","eslint-plugin-unused-imports":"^2.0.0","husky":"^7.0.4","jest":"^29.3.1","lint-staged":"^12.3.7","netlify-cli":"^17.26.2","nodemon":"^2.0.15","prettier":"^2.6.0","pretty-quick":"^3.1.3","rollup":"^2.70.1","ts-jest":"^29.1.0","ts-morph":"^14.0.0","ts-node":"^10.9.1","tslib":"^2.3.1","tsx":"^3.8.0","typescript":"~4.5.5","vitest":"^0.32.2"},"exports":{".":{"types":"./index.d.ts","require":"./lib/index.js","import":"./lib/index.mjs"},"./package.json":"./package.json","./locales/*":"./lib/locales/*"},"bugs":{"url":"https://github.com/colinhacks/zod/issues"},"description":"TypeScript-first schema declaration and validation library with static type inference","funding":"https://github.com/sponsors/colinhacks","homepage":"https://zod.dev","keywords":["typescript","schema","validation","type","inference"],"license":"MIT","lint-staged":{"src/*.ts":["eslint --cache --fix","prettier --ignore-unknown --write"],"*.md":["prettier --ignore-unknown --write"]},"scripts":{"prettier:check":"prettier --check src/**/*.ts deno/lib/**/*.ts *.md --no-error-on-unmatched-pattern","prettier:fix":"prettier --write src/**/*.ts deno/lib/**/*.ts *.md --ignore-unknown --no-error-on-unmatched-pattern","lint:check":"eslint --cache --ext .ts ./src","lint:fix":"eslint --cache --fix --ext .ts ./src","check":"yarn lint:check && yarn prettier:check","fix":"yarn lint:fix && yarn prettier:fix","clean":"rm -rf lib/* deno/lib/*","build":"yarn run clean && npm run build:cjs && npm run build:esm && npm run build:deno","build:deno":"node ./deno-build.mjs && cp ./README.md ./deno/lib","build:esm":"rollup --config ./configs/rollup.config.js","build:cjs":"tsc -p ./configs/tsconfig.cjs.json","build:types":"tsc -p ./configs/tsconfig.types.json","build:test":"tsc -p ./configs/tsconfig.test.json","test:watch":"yarn test:ts-jest --watch","test":"yarn test:ts-jest","test:babel":"jest --coverage --config ./configs/babel-jest.config.json","test:bun":"bun test src/","test:vitest":"npx vitest --config ./configs/vitest.config.ts","test:ts-jest":"npx jest --config ./configs/ts-jest.config.json","test:swc":"npx jest --config ./configs/swc-jest.config.json","test:deno":"cd deno && deno test","prepublishOnly":"npm run test && npm run build && npm run build:deno","play":"nodemon -e ts -w . -x tsx playground.ts","depcruise":"depcruise -c .dependency-cruiser.js src","benchmark":"tsx src/benchmarks/index.ts","prepare":"husky install","docs":"netlify dev"},"sideEffects":false,"support":{"backing":{"npm-funding":true}},"types":"./index.d.ts","_id":"zod@3.24.0-canary.20240701T200529","readme":"<p align=\"center\">\n  <img src=\"logo.svg\" width=\"200px\" align=\"center\" alt=\"Zod logo\" />\n  <h1 align=\"center\">Zod</h1>\n  <p align=\"center\">\n    ✨ <a href=\"https://zod.dev\">https://zod.dev</a> ✨\n    <br/>\n    TypeScript-first schema validation with static type inference\n  </p>\n</p>\n<br/>\n<p align=\"center\">\n<a href=\"https://github.com/colinhacks/zod/actions?query=branch%3Amain\"><img src=\"https://github.com/colinhacks/zod/actions/workflows/test.yml/badge.svg?event=push&branch=main\" alt=\"Zod CI status\" /></a>\n<a href=\"https://twitter.com/colinhacks\" rel=\"nofollow\"><img src=\"https://img.shields.io/badge/created%20by-@colinhacks-4BBAAB.svg\" alt=\"Created by Colin McDonnell\"></a>\n<a href=\"https://opensource.org/licenses/MIT\" rel=\"nofollow\"><img src=\"https://img.shields.io/github/license/colinhacks/zod\" alt=\"License\"></a>\n<a href=\"https://www.npmjs.com/package/zod\" rel=\"nofollow\"><img src=\"https://img.shields.io/npm/dw/zod.svg\" alt=\"npm\"></a>\n<a href=\"https://www.npmjs.com/package/zod\" rel=\"nofollow\"><img src=\"https://img.shields.io/github/stars/colinhacks/zod\" alt=\"stars\"></a>\n</p>\n\n<div align=\"center\">\n  <a href=\"https://zod.dev\">Documentation</a>\n  <span>&nbsp;&nbsp;•&nbsp;&nbsp;</span>\n  <a href=\"https://discord.gg/RcG33DQJdf\">Discord</a>\n  <span>&nbsp;&nbsp;•&nbsp;&nbsp;</span>\n  <a href=\"https://www.npmjs.com/package/zod\">npm</a>\n  <span>&nbsp;&nbsp;•&nbsp;&nbsp;</span>\n  <a href=\"https://deno.land/x/zod\">deno</a>\n  <span>&nbsp;&nbsp;•&nbsp;&nbsp;</span>\n  <a href=\"https://github.com/colinhacks/zod/issues/new\">Issues</a>\n  <span>&nbsp;&nbsp;•&nbsp;&nbsp;</span>\n  <a href=\"https://twitter.com/colinhacks\">@colinhacks</a>\n  <span>&nbsp;&nbsp;•&nbsp;&nbsp;</span>\n  <a href=\"https://trpc.io\">tRPC</a>\n  <br />\n</div>\n\n<br/>\n<br/>\n\n<!-- <p><strong>Announcement ✨</strong> Zod has recieved the <a href=\"https://go.clerk.com/zod-clerk\">Clerk</a> OSS Fellowship!<br/>Read the announcement post 👉 <a href=\"https://go.clerk.com/zod-clerk\">clerk.com/blog/zod-fellowship</a></p> -->\n\n[![clerk announcement](https://github.com/colinhacks/zod/assets/3084745/6327cf99-8d82-4b44-a5b1-ba2b5c2ff6ad)](https://go.clerk.com/hqN4rp7)\n\n<br/>\n\n## Table of contents\n\n> These docs have been translated into [Chinese](./README_ZH.md).\n\n- [Table of contents](#table-of-contents)\n- [Introduction](#introduction)\n  - [Sponsors](#sponsors)\n    - [Platinum](#platinum)\n    - [Gold](#gold)\n    - [Silver](#silver)\n    - [Bronze](#bronze)\n    - [Copper](#copper)\n  - [Ecosystem](#ecosystem)\n    - [Resources](#resources)\n    - [API libraries](#api-libraries)\n    - [Form integrations](#form-integrations)\n    - [Zod to X](#zod-to-x)\n    - [X to Zod](#x-to-zod)\n    - [Mocking](#mocking)\n    - [Powered by Zod](#powered-by-zod)\n    - [Utilities for Zod](#utilities-for-zod)\n- [Installation](#installation)\n  - [Requirements](#requirements)\n  - [From `npm` (Node/Bun)](#from-npm-nodebun)\n  - [From `deno.land/x` (Deno)](#from-denolandx-deno)\n- [Basic usage](#basic-usage)\n- [Primitives](#primitives)\n- [Coercion for primitives](#coercion-for-primitives)\n- [Literals](#literals)\n- [Strings](#strings)\n  - [Datetimes](#datetimes)\n  - [Dates](#dates)\n  - [Times](#times)\n  - [IP addresses](#ip-addresses)\n- [Numbers](#numbers)\n- [BigInts](#bigints)\n- [NaNs](#nans)\n- [Booleans](#booleans)\n- [Dates](#dates)\n- [Zod enums](#zod-enums)\n- [Native enums](#native-enums)\n- [Optionals](#optionals)\n- [Nullables](#nullables)\n- [Objects](#objects)\n  - [`.shape`](#shape)\n  - [`.keyof`](#keyof)\n  - [`.extend`](#extend)\n  - [`.merge`](#merge)\n  - [`.pick/.omit`](#pickomit)\n  - [`.partial`](#partial)\n  - [`.deepPartial`](#deeppartial)\n  - [`.required`](#required)\n  - [`.passthrough`](#passthrough)\n  - [`.strict`](#strict)\n  - [`.strip`](#strip)\n  - [`.catchall`](#catchall)\n- [Arrays](#arrays)\n  - [`.element`](#element)\n  - [`.nonempty`](#nonempty)\n  - [`.min/.max/.length`](#minmaxlength)\n- [Tuples](#tuples)\n- [Unions](#unions)\n- [Discriminated unions](#discriminated-unions)\n- [Records](#records)\n  - [Record key type](#record-key-type)\n- [Maps](#maps)\n- [Sets](#sets)\n- [Intersections](#intersections)\n- [Recursive types](#recursive-types)\n  - [ZodType with ZodEffects](#zodtype-with-zodeffects)\n  - [JSON type](#json-type)\n  - [Cyclical objects](#cyclical-objects)\n- [Promises](#promises)\n- [Instanceof](#instanceof)\n- [Functions](#functions)\n- [Preprocess](#preprocess)\n- [Custom schemas](#custom-schemas)\n- [Schema methods](#schema-methods)\n  - [`.parse`](#parse)\n  - [`.parseAsync`](#parseasync)\n  - [`.safeParse`](#safeparse)\n  - [`.safeParseAsync`](#safeparseasync)\n  - [`.refine`](#refine)\n    - [Arguments](#arguments)\n    - [Customize error path](#customize-error-path)\n    - [Asynchronous refinements](#asynchronous-refinements)\n    - [Relationship to transforms](#relationship-to-transforms)\n  - [`.superRefine`](#superrefine)\n    - [Abort early](#abort-early)\n    - [Type refinements](#type-refinements)\n  - [`.transform`](#transform)\n    - [Chaining order](#chaining-order)\n    - [Validating during transform](#validating-during-transform)\n    - [Relationship to refinements](#relationship-to-refinements)\n    - [Async transforms](#async-transforms)\n  - [`.default`](#default)\n  - [`.describe`](#describe)\n  - [`.catch`](#catch)\n  - [`.optional`](#optional)\n  - [`.nullable`](#nullable)\n  - [`.nullish`](#nullish)\n  - [`.array`](#array)\n  - [`.promise`](#promise)\n  - [`.or`](#or)\n  - [`.and`](#and)\n  - [`.brand`](#brand)\n  - [`.readonly`](#readonly)\n  - [`.pipe`](#pipe)\n    - [You can use `.pipe()` to fix common issues with `z.coerce`.](#you-can-use-pipe-to-fix-common-issues-with-zcoerce)\n- [Guides and concepts](#guides-and-concepts)\n  - [Type inference](#type-inference)\n  - [Writing generic functions](#writing-generic-functions)\n    - [Constraining allowable inputs](#constraining-allowable-inputs)\n  - [Error handling](#error-handling)\n  - [Error formatting](#error-formatting)\n- [Comparison](#comparison)\n  - [Joi](#joi)\n  - [Yup](#yup)\n  - [io-ts](#io-ts)\n  - [Runtypes](#runtypes)\n  - [Ow](#ow)\n- [Changelog](#changelog)\n\n## Introduction\n\nZod 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.\n\nZod 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.\n\nSome other great aspects:\n\n- Zero dependencies\n- Works in Node.js and all modern browsers\n- Tiny: 8kb minified + zipped\n- Immutable: methods (e.g. `.optional()`) return a new instance\n- Concise, chainable interface\n- Functional approach: [parse, don't validate](https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-validate/)\n- Works with plain JavaScript too! You don't need to use TypeScript.\n\n## Sponsors\n\nSponsorship at any level is appreciated and encouraged. If you built a paid product using Zod, consider one of the [corporate tiers](https://github.com/sponsors/colinhacks).\n\n<br/>\n<h3 align=\"center\">Diamond</h3>\n\n<br/>\n\n<div align=\"center\">\n  <a href=\"https://go.clerk.com/PKHrcwh\">\n    <picture width=\"100%\">\n      <source media=\"(prefers-color-scheme: dark)\" srcset=\"https://github.com/colinhacks/zod/assets/3084745/15c8c8be-189d-44ed-b3db-59bf2a21cbe3\">\n      <img alt=\"clerk logo\" src=\"https://github.com/colinhacks/zod/assets/3084745/15c8c8be-189d-44ed-b3db-59bf2a21cbe3\">\n    </picture>\n  </a>\n  <br/>\n  <br/>\n  <p>\n    The most comprehensive User Management Platform\n    <br/>\n    <a style=\"text-decoration:none;\" href=\"https://go.clerk.com/PKHrcwh\" target=\"_blank\">clerk.com</a>\n  </p>\n</div>\n\n<br/>\n<br/>\n\n<h3 align=\"center\">Platinum</h3>\n\n<table align=\"center\" style=\"justify-content: center;align-items: center;display: flex;\">\n  <tr>\n    <td align=\"center\">\n      <p></p>\n      <p>\n      <a href=\"https://speakeasyapi.dev/?utm_source=zod+docs\">\n        <picture height=\"40px\">\n          <source media=\"(prefers-color-scheme: dark)\" srcset=\"https://github.com/colinhacks/zod/assets/3084745/b1d86601-c7fb-483c-9927-5dc24ce8b737\">\n          <img alt=\"speakeasy\" height=\"40px\" src=\"https://github.com/colinhacks/zod/assets/3084745/647524a4-22bb-4199-be70-404207a5a2b5\">\n        </picture>\n      </a>\n      <br  />   \n      SDKs & Terraform providers for your API\n      <br/>\n      <a href=\"https://speakeasyapi.dev/?utm_source=zod+docs\" style=\"text-decoration:none;\">speakeasyapi.dev</a>\n      </p>\n      <p></p>\n    </td>\n    </tr><tr>\n     <td align=\"center\">\n      <p></p>\n      <p>\n      <a href=\"https://stainlessapi.com\">\n        <picture height=\"45px\">\n          <source media=\"(prefers-color-scheme: dark)\" srcset=\"https://github.com/colinhacks/zod/assets/3084745/f20759c1-3e51-49d0-a31e-bbc43abec665\">\n          <img alt=\"stainless\" height=\"45px\" src=\"https://github.com/colinhacks/zod/assets/3084745/e9444e44-d991-4bba-a697-dbcfad608e47\">\n        </picture>\n      </a>\n      <br  />   \n      Generate best-in-class SDKs\n      <br/>\n      <a href=\"https://stainlessapi.com\" style=\"text-decoration:none;\">stainlessapi.com</a>\n      </p>\n      <p></p>\n    </td>\n  </tr>\n</table>\n\n<br/>\n\n<h3 align=\"center\">Gold</h3>\n\n<table align=\"center\" style=\"justify-content: center;align-items: center;display: flex;\">\n  <tr>\n    <td align=\"center\">\n      <img src=\"https://avatars.githubusercontent.com/u/89474619?s=200&v=4\" height=\"50px;\" alt=\"PropelAuth\" />\n      <br />\n      <a style=\"text-decoration:none;\" href=\"https://www.propelauth.com/\" target=\"_blank\">PropelAuth</a>\n    </td>\n    <td align=\"center\">\n      <img src=\"https://avatars.githubusercontent.com/u/80861386?s=200&v=4\" height=\"50px;\" alt=\"Cerbos\" />\n      <br />\n      <a style=\"text-decoration:none;\" href=\"https://cerbos.dev/\" target=\"_blank\">Cerbos</a>\n    </td>\n    <td align=\"center\">\n      <img src=\"https://avatars.githubusercontent.com/u/301879?s=200&v=4\" height=\"50px;\" alt=\"Scalar.com logo\" />\n      <br />\n      <a style=\"text-decoration:none;\" href=\"https://scalar.com/\" target=\"_blank\">Scalar</a>\n    </td>\n    <td align=\"center\">\n      <img src=\"https://avatars.githubusercontent.com/u/95297378?s=200&v=4\" height=\"50px;\" alt=\"Trigger.dev logo\" />\n      <br />\n      <a style=\"text-decoration:none;\" href=\"https://trigger.dev\" target=\"_blank\">Trigger.dev</a>\n    </td>\n    </tr><tr>\n    <td align=\"center\">\n      <img src=\"https://avatars.githubusercontent.com/u/125754?s=200&v=4\" height=\"50px;\" alt=\"Transloadit logo\" />\n      <br />\n      <a style=\"text-decoration:none;\" href=\"https://transloadit.com/?utm_source=zod&utm_medium=refe\n    rral&utm_campaign=sponsorship&utm_content=github\" target=\"_blank\">Transloadit</a>\n    </td>\n    <td align=\"center\">\n      <img src=\"https://avatars.githubusercontent.com/u/107880645?s=200&v=4\" height=\"50px;\" alt=\"Infisical logo\" />\n      <br />\n      <a style=\"text-decoration:none;\" href=\"https://infisical.com\" target=\"_blank\">Infisical</a>\n    </td>\n    <td align=\"center\">\n      <img src=\"https://avatars.githubusercontent.com/u/91036480?s=200&v=4\" height=\"50px;\" alt=\"Whop logo\" />\n      <br />\n      <a style=\"text-decoration:none;\" href=\"https://whop.com/\" target=\"_blank\">Whop</a>\n    </td>\n    <td align=\"center\">\n      <img src=\"https://avatars.githubusercontent.com/u/36402888?s=200&v=4\" height=\"50px;\" alt=\"CryptoJobsList logo\" />\n      <br />\n      <a style=\"text-decoration:none;\" href=\"https://cryptojobslist.com/\" target=\"_blank\">CryptoJobsList</a>\n    </td>\n    </tr><tr>\n    <td align=\"center\">\n      <img src=\"https://avatars.githubusercontent.com/u/70170949?s=200&v=4\" height=\"50px;\" alt=\"Plain logo\" />\n      <br />\n      <a style=\"text-decoration:none;\" href=\"https://plain.com/\" target=\"_blank\">Plain.</a>\n    </td>\n    <td align=\"center\">\n      <img src=\"https://avatars.githubusercontent.com/u/78935958?s=200&v=4\" height=\"50px;\" alt=\"Inngest logo\" />\n      <br />\n      <a style=\"text-decoration:none;\" href=\"https://inngest.com/\" target=\"_blank\">Inngest</a>\n    </td>\n    <td align=\"center\">\n      <img src=\"https://avatars.githubusercontent.com/u/13880908?s=200&v=4\" height=\"50px;\" alt=\"Storyblok CMS\" />\n      <br />\n      <a style=\"text-decoration:none;\" href=\"https://storyblok.com/\" target=\"_blank\">Storyblok</a>\n    </td>\n    <td align=\"center\">\n      <img src=\"https://avatars.githubusercontent.com/u/16199997?s=200&v=4\" height=\"50px;\" alt=\"Mux logo\" />\n      <br />\n      <a style=\"text-decoration:none;\" href=\"https://mux.link/zod\" target=\"_blank\">Mux</a>\n    </td>\n  </tr>\n</table>\n\n<br/>\n\n<h3 align=\"center\">Silver</h3>\n\n<table align=\"center\" style=\"justify-content: center;align-items: center;display: flex;\">\n  <tr>\n    <td align=\"center\">\n      <a href=\"https://www.route4me.com/\">\n        <img src=\"https://avatars.githubusercontent.com/u/7936820?s=200&v=4\" height=\"40px;\" alt=\"route4me logo\" />\n      </a>\n    </td>\n    <td align=\"center\">\n      <a href=\"https://encore.dev\">\n        <img src=\"https://github.com/colinhacks/zod/assets/3084745/5ad94e73-cd34-4957-9979-37da85fcf9cd\" height=\"40px;\" alt=\"Encore.dev logo\" />\n      </a>\n    </td>\n    <td align=\"center\">\n      <a href=\"https://www.replay.io/\">\n        <img src=\"https://avatars.githubusercontent.com/u/60818315?s=200&v=4\" height=\"40px;\" alt=\"Replay.io logo\" />\n      </a>\n    </td>\n    <td align=\"center\">\n      <a href=\"https://www.numeric.io\">\n        <img src=\"https://i.imgur.com/kTiLtZt.png\" height=\"40px;\" alt=\"Numeric logo\" />\n      </a>\n    </td>\n  </tr>\n  <tr>\n    <td align=\"center\">\n      <a href=\"https://marcatopartners.com\">\n        <img src=\"https://avatars.githubusercontent.com/u/84106192?s=200&v=4\" height=\"40px;\" alt=\"Marcato Partners\" />\n      </a>\n    </td>\n    <td align=\"center\">\n      <a href=\"https://interval.com\">\n        <img src=\"https://avatars.githubusercontent.com/u/67802063?s=200&v=4\" height=\"40px;\" alt=\"\" />\n      </a>\n    </td>\n    <td align=\"center\">\n      <a href=\"https://seasoned.cc\">\n        <img src=\"https://avatars.githubusercontent.com/u/33913103?s=200&v=4\" height=\"40px;\" alt=\"\" />\n      </a>\n    </td>\n    <td align=\"center\">\n      <a href=\"https://www.bamboocreative.nz/\">\n        <img src=\"https://avatars.githubusercontent.com/u/41406870?v=4\" height=\"40px;\" alt=\"Bamboo Creative logo\" />\n      </a>\n    </td>\n  </tr>\n  <tr>\n    <td align=\"center\">\n      <a href=\"https://github.com/jasonLaster\">\n        <img src=\"https://avatars.githubusercontent.com/u/254562?v=4\" height=\"40px;\" alt=\"Jason Laster\" />\n      </a>\n    </td>\n  </tr>\n</table>\n\n<h3 align=\"center\">Bronze</h3>\n\n<table align=\"center\" style=\"justify-content: center;align-items: center;display: flex;\">\n  <tr>\n    <td>Brandon Bayer</td>\n    <td>Jiří Brabec</td>\n    <td>Alex Johansson</td>\n    <td>Fungible Systems</td>\n  </tr>\n  <tr>\n    <td>Adaptable</td>\n    <td>Avana Wallet</td>\n    <td>Jason Lengstorf</td>\n    <td>Global Illumination, Inc.</td>\n  </tr>\n  <tr>\n    <td>MasterBorn</td>\n    <td>Ryan Palmer</td>\n    <td>Michael Sweeney</td>\n    <td>Nextbase</td>\n  </tr>\n  <tr>\n    <td>Remotion</td>\n    <td>Connor Sinnott</td>\n    <td>Mohammad-Ali A'râbi</td>\n    <td>Supatool</td>\n  </tr>\n</table>\n\n### Ecosystem\n\nThere 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](https://twitter.com/colinhacks) or [start a Discussion](https://github.com/colinhacks/zod/discussions). I'll add it below and tweet it out.\n\n#### Resources\n\n- [Total TypeScript Zod Tutorial](https://www.totaltypescript.com/tutorials/zod) by [@mattpocockuk](https://twitter.com/mattpocockuk)\n- [Fixing TypeScript's Blindspot: Runtime Typechecking](https://www.youtube.com/watch?v=rY_XqfSHock) by [@jherr](https://twitter.com/jherr)\n\n#### API libraries\n\n- [`tRPC`](https://github.com/trpc/trpc): Build end-to-end typesafe APIs without GraphQL.\n- [`@anatine/zod-nestjs`](https://github.com/anatine/zod-plugins/tree/main/packages/zod-nestjs): Helper methods for using Zod in a NestJS project.\n- [`zod-endpoints`](https://github.com/flock-community/zod-endpoints): Contract-first strictly typed endpoints with Zod. OpenAPI compatible.\n- [`zhttp`](https://github.com/evertdespiegeleer/zhttp): An OpenAPI compatible, strictly typed http library with Zod input and response validation.\n- [`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.\n- [`@zodios/core`](https://github.com/ecyrbe/zodios): A typescript API client with runtime and compile time validation backed by axios and zod.\n- [`express-zod-api`](https://github.com/RobinTail/express-zod-api): Build Express-based APIs with I/O schema validation and custom middlewares.\n- [`tapiduck`](https://github.com/sumukhbarve/monoduck/blob/main/src/tapiduck/README.md): End-to-end typesafe JSON APIs with Zod and Express; a bit like tRPC, but simpler.\n- [`koa-zod-router`](https://github.com/JakeFenley/koa-zod-router): Create typesafe routes in Koa with I/O validation using Zod.\n- [`zod-sockets`](https://github.com/RobinTail/zod-sockets): Zod-powered Socket.IO microframework with I/O validation and built-in AsyncAPI specs\n\n#### Form integrations\n\n- [`react-hook-form`](https://github.com/react-hook-form/resolvers#zod): A first-party Zod resolver for React Hook Form.\n- [`zod-validation-error`](https://github.com/causaly/zod-validation-error): Generate user-friendly error messages from `ZodError`s.\n- [`zod-formik-adapter`](https://github.com/robertLichtnow/zod-formik-adapter): A community-maintained Formik adapter for Zod.\n- [`react-zorm`](https://github.com/esamattis/react-zorm): Standalone `<form>` generation and validation for React using Zod.\n- [`zodix`](https://github.com/rileytomasek/zodix): Zod utilities for FormData and URLSearchParams in Remix loaders and actions.\n- [`conform`](https://conform.guide/api/zod/parseWithZod): A typesafe form validation library for progressive enhancement of HTML forms. Works with Remix and Next.js.\n- [`remix-params-helper`](https://github.com/kiliman/remix-params-helper): Simplify integration of Zod with standard URLSearchParams and FormData for Remix apps.\n- [`formik-validator-zod`](https://github.com/glazy/formik-validator-zod): Formik-compliant validator library that simplifies using Zod with Formik.\n- [`zod-i18n-map`](https://github.com/aiji42/zod-i18n): Useful for translating Zod error messages.\n- [`@modular-forms/solid`](https://github.com/fabian-hiller/modular-forms): Modular form library for SolidJS that supports Zod for validation.\n- [`houseform`](https://github.com/crutchcorn/houseform/): A React form library that uses Zod for validation.\n- [`sveltekit-superforms`](https://github.com/ciscoheat/sveltekit-superforms): Supercharged form library for SvelteKit with Zod validation.\n- [`mobx-zod-form`](https://github.com/MonoidDev/mobx-zod-form): Data-first form builder based on MobX & Zod.\n- [`@vee-validate/zod`](https://github.com/logaretm/vee-validate/tree/main/packages/zod): Form library for Vue.js with Zod schema validation.\n\n#### Zod to X\n\n- [`zod-to-ts`](https://github.com/sachinraja/zod-to-ts): Generate TypeScript definitions from Zod schemas.\n- [`zod-to-json-schema`](https://github.com/StefanTerdell/zod-to-json-schema): Convert your Zod schemas into [JSON Schemas](https://json-schema.org/).\n- [`@anatine/zod-openapi`](https://github.com/anatine/zod-plugins/tree/main/packages/zod-openapi): Converts a Zod schema to an OpenAPI v3.x `SchemaObject`.\n- [`zod-fast-check`](https://github.com/DavidTimms/zod-fast-check): Generate `fast-check` arbitraries from Zod schemas.\n- [`zod-dto`](https://github.com/kbkk/abitia/tree/main/packages/zod-dto): Generate Nest.js DTOs from a Zod schema.\n- [`fastify-type-provider-zod`](https://github.com/turkerdev/fastify-type-provider-zod): Create Fastify type providers from Zod schemas.\n- [`zod-to-openapi`](https://github.com/asteasolutions/zod-to-openapi): Generate full OpenAPI (Swagger) docs from Zod, including schemas, endpoints & parameters.\n- [`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.\n- [`zod-openapi`](https://github.com/samchungy/zod-openapi): Create full OpenAPI v3.x documentation from Zod schemas.\n- [`fastify-zod-openapi`](https://github.com/samchungy/fastify-zod-openapi): Fastify type provider, validation, serialization and @fastify/swagger support for Zod schemas.\n- [`typeschema`](https://typeschema.com/): Universal adapter for schema validation.\n\n#### X to Zod\n\n- [`ts-to-zod`](https://github.com/fabien0102/ts-to-zod): Convert TypeScript definitions into Zod schemas.\n- [`@runtyping/zod`](https://github.com/johngeorgewright/runtyping/tree/main/packages/zod): Generate Zod from static types & JSON schema.\n- [`json-schema-to-zod`](https://github.com/StefanTerdell/json-schema-to-zod): Convert your [JSON Schemas](https://json-schema.org/) into Zod schemas. [Live demo](https://StefanTerdell.github.io/json-schema-to-zod-react/).\n- [`json-to-zod`](https://github.com/rsinohara/json-to-zod): Convert JSON objects into Zod schemas. [Live demo](https://rsinohara.github.io/json-to-zod-react/).\n- [`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.\n- [`zod-prisma`](https://github.com/CarterGrimmeisen/zod-prisma): Generate Zod schemas from your Prisma schema.\n- [`Supervillain`](https://github.com/Southclaws/supervillain): Generate Zod schemas from your Go structs.\n- [`prisma-zod-generator`](https://github.com/omar-dulaimi/prisma-zod-generator): Emit Zod schemas from your Prisma schema.\n- [`prisma-trpc-generator`](https://github.com/omar-dulaimi/prisma-trpc-generator): Emit fully implemented tRPC routers and their validation schemas using Zod.\n- [`zod-prisma-types`](https://github.com/chrishoermann/zod-prisma-types) Create Zod types from your Prisma models.\n- [`quicktype`](https://app.quicktype.io/): Convert JSON objects and JSON schemas into Zod schemas.\n- [`@sanity-typed/zod`](https://github.com/saiichihashimoto/sanity-typed/tree/main/packages/zod): Generate Zod Schemas from [Sanity Schemas](https://www.sanity.io/docs/schema-types).\n- [`java-to-zod`](https://github.com/ivangreene/java-to-zod): Convert POJOs to Zod schemas\n- [`Orval`](https://github.com/anymaniax/orval): Generate Zod schemas from OpenAPI schemas\n- [`Kubb`](https://github.com/kubb-labs/kubb): Generate SDKs and Zod schemas from your OpenAPI schemas\n\n#### Mocking\n\n- [`@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](https://github.com/faker-js/faker).\n- [`zod-mocking`](https://github.com/dipasqualew/zod-mocking): Generate mock data from your Zod schemas.\n- [`zod-fixture`](https://github.com/timdeschryver/zod-fixture): Use your zod schemas to automate the generation of non-relevant test fixtures in a deterministic way.\n- [`zocker`](https://zocker.sigrist.dev): Generate plausible mock-data from your schemas.\n- [`zodock`](https://github.com/ItMaga/zodock) Generate mock data based on Zod schemas.\n- [`zod-schema-faker`](https://github.com/soc221b/zod-schema-faker) Generates mock data from Zod schemas. Powered by [@faker-js/faker](https://github.com/faker-js/faker) and [randexp.js](https://github.com/fent/randexp.js)\n\n#### Powered by Zod\n\n- [`freerstore`](https://github.com/JacobWeisenburger/freerstore): Firestore cost optimizer.\n- [`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.\n- [`soly`](https://github.com/mdbetancourt/soly): Create CLI applications with zod.\n- [`pastel`](https://github.com/vadimdemedes/pastel): Create CLI applications with react, zod, and ink.\n- [`zod-xlsx`](https://github.com/sidwebworks/zod-xlsx): A xlsx based resource validator using Zod schemas.\n- [`znv`](https://github.com/lostfictions/znv): Type-safe environment parsing and validation for Node.js with Zod schemas.\n- [`zod-config`](https://github.com/alexmarqs/zod-config): Load configurations across multiple sources with flexible adapters, ensuring type safety with Zod.\n\n#### Utilities for Zod\n\n- [`zod_utilz`](https://github.com/JacobWeisenburger/zod_utilz): Framework agnostic utilities for Zod.\n- [`zod-playground`](https://github.com/marilari88/zod-playground): A tool for learning and testing Zod schema validation functionalities. [Link](https://zod-playground.vercel.app/).\n- [`zod-sandbox`](https://github.com/nereumelo/zod-sandbox): Controlled environment for testing zod schemas. [Live demo](https://zod-sandbox.vercel.app/).\n- [`zod-dev`](https://github.com/schalkventer/zod-dev): Conditionally disables Zod runtime parsing in production.\n- [`zod-accelerator`](https://github.com/duplojs/duplojs-zod-accelerator): Accelerates Zod's throughput up to ~100x.\n\n## Installation\n\n### Requirements\n\n- TypeScript 4.5+!\n- You must enable `strict` mode in your `tsconfig.json`. This is a best practice for all TypeScript projects.\n\n  ```ts\n  // tsconfig.json\n  {\n    // ...\n    \"compilerOptions\": {\n      // ...\n      \"strict\": true\n    }\n  }\n  ```\n\n### From `npm` (Node/Bun)\n\n```sh\nnpm install zod       # npm\nyarn add zod          # yarn\nbun add zod           # bun\npnpm add zod          # pnpm\n```\n\nZod also publishes a canary version on every commit. To install the canary:\n\n```sh\nnpm install zod@canary       # npm\nyarn add zod@canary          # yarn\nbun add zod@canary           # bun\npnpm add zod@canary          # pnpm\n```\n\n### From `deno.land/x` (Deno)\n\nUnlike Node, Deno relies on direct URL imports instead of a package manager like NPM. Zod is available on [deno.land/x](https://deno.land/x). The latest version can be imported like so:\n\n```ts\nimport { z } from \"https://deno.land/x/zod/mod.ts\";\n```\n\nYou can also specify a particular version:\n\n```ts\nimport { z } from \"https://deno.land/x/zod@v3.16.1/mod.ts\";\n```\n\n> The rest of this README assumes you are using npm and importing directly from the `\"zod\"` package.\n\n## Basic usage\n\nCreating a simple string schema\n\n```ts\nimport { z } from \"zod\";\n\n// creating a schema for strings\nconst mySchema = z.string();\n\n// parsing\nmySchema.parse(\"tuna\"); // => \"tuna\"\nmySchema.parse(12); // => throws ZodError\n\n// \"safe\" parsing (doesn't throw error if validation fails)\nmySchema.safeParse(\"tuna\"); // => { success: true; data: \"tuna\" }\nmySchema.safeParse(12); // => { success: false; error: ZodError }\n```\n\nCreating an object schema\n\n```ts\nimport { z } from \"zod\";\n\nconst User = z.object({\n  username: z.string(),\n});\n\nUser.parse({ username: \"Ludwig\" });\n\n// extract the inferred type\ntype User = z.infer<typeof User>;\n// { username: string }\n```\n\n## Primitives\n\n```ts\nimport { z } from \"zod\";\n\n// primitive values\nz.string();\nz.number();\nz.bigint();\nz.boolean();\nz.date();\nz.symbol();\n\n// empty types\nz.undefined();\nz.null();\nz.void(); // accepts undefined\n\n// catch-all types\n// allows any value\nz.any();\nz.unknown();\n\n// never type\n// allows no values\nz.never();\n```\n\n## Coercion for primitives\n\nZod now provides a more convenient way to coerce primitive values.\n\n```ts\nconst schema = z.coerce.string();\nschema.parse(\"tuna\"); // => \"tuna\"\nschema.parse(12); // => \"12\"\n```\n\nDuring the parsing step, the input is passed through the `String()` function, which is a JavaScript built-in for coercing data into strings.\n\n```ts\nschema.parse(12); // => \"12\"\nschema.parse(true); // => \"true\"\nschema.parse(undefined); // => \"undefined\"\nschema.parse(null); // => \"null\"\n```\n\nThe returned schema is a normal `ZodString` instance so you can use all string methods.\n\n```ts\nz.coerce.string().email().min(5);\n```\n\n**How coercion works**\n\nAll primitive types support coercion. Zod coerces all inputs using the built-in constructors: `String(input)`, `Number(input)`, `new Date(input)`, etc.\n\n```ts\nz.coerce.string(); // String(input)\nz.coerce.number(); // Number(input)\nz.coerce.boolean(); // Boolean(input)\nz.coerce.bigint(); // BigInt(input)\nz.coerce.date(); // new Date(input)\n```\n\n**Note** — Boolean coercion with `z.coerce.boolean()` may not work how you expect. Any [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy) value is coerced to `true`, and any [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) value is coerced to `false`.\n\n```ts\nconst schema = z.coerce.boolean(); // Boolean(input)\n\nschema.parse(\"tuna\"); // => true\nschema.parse(\"true\"); // => true\nschema.parse(\"false\"); // => true\nschema.parse(1); // => true\nschema.parse([]); // => true\n\nschema.parse(0); // => false\nschema.parse(\"\"); // => false\nschema.parse(undefined); // => false\nschema.parse(null); // => false\n```\n\nFor more control over coercion logic, consider using [`z.preprocess`](#preprocess) or [`z.pipe()`](#pipe).\n\n## Literals\n\nLiteral schemas represent a [literal type](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#literal-types), like `\"hello world\"` or `5`.\n\n```ts\nconst tuna = z.literal(\"tuna\");\nconst twelve = z.literal(12);\nconst twobig = z.literal(2n); // bigint literal\nconst tru = z.literal(true);\n\nconst terrificSymbol = Symbol(\"terrific\");\nconst terrific = z.literal(terrificSymbol);\n\n// retrieve literal value\ntuna.value; // \"tuna\"\n```\n\n> Currently there is no support for Date literals in Zod. If you have a use case for this feature, please file an issue.\n\n## Strings\n\nZod includes a handful of string-specific validations.\n\n```ts\n// validations\nz.string().max(5);\nz.string().min(5);\nz.string().length(5);\nz.string().email();\nz.string().url();\nz.string().emoji();\nz.string().uuid();\nz.string().nanoid();\nz.string().cuid();\nz.string().cuid2();\nz.string().ulid();\nz.string().regex(regex);\nz.string().includes(string);\nz.string().startsWith(string);\nz.string().endsWith(string);\nz.string().datetime(); // ISO 8601; by default only `Z` timezone allowed\nz.string().ip(); // defaults to allow both IPv4 and IPv6\n\n// transforms\nz.string().trim(); // trim whitespace\nz.string().toLowerCase(); // toLowerCase\nz.string().toUpperCase(); // toUpperCase\n\n// added in Zod 3.23\nz.string().date(); // ISO date format (YYYY-MM-DD)\nz.string().time(); // ISO time format (HH:mm:ss[.SSSSSS])\nz.string().duration(); // ISO 8601 duration\nz.string().base64();\n```\n\n> Check out [validator.js](https://github.com/validatorjs/validator.js) for a bunch of other useful string validation functions that can be used in conjunction with [Refinements](#refine).\n\nYou can customize some common error messages when creating a string schema.\n\n```ts\nconst name = z.string({\n  required_error: \"Name is required\",\n  invalid_type_error: \"Name must be a string\",\n});\n```\n\nWhen using validation methods, you can pass in an additional argument to provide a custom error message.\n\n```ts\nz.string().min(5, { message: \"Must be 5 or more characters long\" });\nz.string().max(5, { message: \"Must be 5 or fewer characters long\" });\nz.string().length(5, { message: \"Must be exactly 5 characters long\" });\nz.string().email({ message: \"Invalid email address\" });\nz.string().url({ message: \"Invalid url\" });\nz.string().emoji({ message: \"Contains non-emoji characters\" });\nz.string().uuid({ message: \"Invalid UUID\" });\nz.string().includes(\"tuna\", { message: \"Must include tuna\" });\nz.string().startsWith(\"https://\", { message: \"Must provide secure URL\" });\nz.string().endsWith(\".com\", { message: \"Only .com domains allowed\" });\nz.string().datetime({ message: \"Invalid datetime string! Must be UTC.\" });\nz.string().date({ message: \"Invalid date string!\" });\nz.string().time({ message: \"Invalid time string!\" });\nz.string().ip({ message: \"Invalid IP address\" });\n```\n\n### Datetimes\n\nAs you may have noticed, Zod string includes a few date/time related validations. These validations are regular expression based, so they are not as strict as a full date/time library. However, they are very convenient for validating user input.\n\nThe `z.string().datetime()` method enforces ISO 8601; default is no timezone offsets and arbitrary sub-second decimal precision.\n\n```ts\nconst datetime = z.string().datetime();\n\ndatetime.parse(\"2020-01-01T00:00:00Z\"); // pass\ndatetime.parse(\"2020-01-01T00:00:00.123Z\"); // pass\ndatetime.parse(\"2020-01-01T00:00:00.123456Z\"); // pass (arbitrary precision)\ndatetime.parse(\"2020-01-01T00:00:00+02:00\"); // fail (no offsets allowed)\n```\n\nTimezone offsets can be allowed by setting the `offset` option to `true`.\n\n```ts\nconst datetime = z.string().datetime({ offset: true });\n\ndatetime.parse(\"2020-01-01T00:00:00+02:00\"); // pass\ndatetime.parse(\"2020-01-01T00:00:00.123+02:00\"); // pass (millis optional)\ndatetime.parse(\"2020-01-01T00:00:00.123+0200\"); // pass (millis optional)\ndatetime.parse(\"2020-01-01T00:00:00.123+02\"); // pass (only offset hours)\ndatetime.parse(\"2020-01-01T00:00:00Z\"); // pass (Z still supported)\n```\n\nYou can additionally constrain the allowable `precision`. By default, arbitrary sub-second precision is supported (but optional).\n\n```ts\nconst datetime = z.string().datetime({ precision: 3 });\n\ndatetime.parse(\"2020-01-01T00:00:00.123Z\"); // pass\ndatetime.parse(\"2020-01-01T00:00:00Z\"); // fail\ndatetime.parse(\"2020-01-01T00:00:00.123456Z\"); // fail\n```\n\n### Dates\n\n> Added in Zod 3.23\n\nThe `z.string().date()` method validates strings in the format `YYYY-MM-DD`.\n\n```ts\nconst date = z.string().date();\n\ndate.parse(\"2020-01-01\"); // pass\ndate.parse(\"2020-1-1\"); // fail\ndate.parse(\"2020-01-32\"); // fail\n```\n\n### Times\n\n> Added in Zod 3.23\n\nThe `z.string().time()` method validates strings in the format `HH:MM:SS[.s+]`. The second can include arbitrary decimal precision. It does not allow timezone offsets of any kind.\n\n```ts\nconst time = z.string().time();\n\ntime.parse(\"00:00:00\"); // pass\ntime.parse(\"09:52:31\"); // pass\ntime.parse(\"23:59:59.9999999\"); // pass (arbitrary precision)\n\ntime.parse(\"00:00:00.123Z\"); // fail (no `Z` allowed)\ntime.parse(\"00:00:00.123+02:00\"); // fail (no offsets allowed)\n```\n\nYou can set the `precision` option to constrain the allowable decimal precision.\n\n```ts\nconst time = z.string().time({ precision: 3 });\n\ntime.parse(\"00:00:00.123\"); // pass\ntime.parse(\"00:00:00.123456\"); // fail\ntime.parse(\"00:00:00\"); // fail\n```\n\n### IP addresses\n\nThe `z.string().ip()` method by default validate IPv4 and IPv6.\n\n```ts\nconst ip = z.string().ip();\n\nip.parse(\"192.168.1.1\"); // pass\nip.parse(\"84d5:51a0:9114:1855:4cfa:f2d7:1f12:7003\"); // pass\nip.parse(\"84d5:51a0:9114:1855:4cfa:f2d7:1f12:192.168.1.1\"); // pass\n\nip.parse(\"256.1.1.1\"); // fail\nip.parse(\"84d5:51a0:9114:gggg:4cfa:f2d7:1f12:7003\"); // fail\n```\n\nYou can additionally set the IP `version`.\n\n```ts\nconst ipv4 = z.string().ip({ version: \"v4\" });\nipv4.parse(\"84d5:51a0:9114:1855:4cfa:f2d7:1f12:7003\"); // fail\n\nconst ipv6 = z.string().ip({ version: \"v6\" });\nipv6.parse(\"192.168.1.1\"); // fail\n```\n\n## Numbers\n\nYou can customize certain error messages when creating a number schema.\n\n```ts\nconst age = z.number({\n  required_error: \"Age is required\",\n  invalid_type_error: \"Age must be a number\",\n});\n```\n\nZod includes a handful of number-specific validations.\n\n```ts\nz.number().gt(5);\nz.number().gte(5); // alias .min(5)\nz.number().lt(5);\nz.number().lte(5); // alias .max(5)\n\nz.number().int(); // value must be an integer\n\nz.number().positive(); //     > 0\nz.number().nonnegative(); //  >= 0\nz.number().negative(); //     < 0\nz.number().nonpositive(); //  <= 0\n\nz.number().multipleOf(5); // Evenly divisible by 5. Alias .step(5)\n\nz.number().finite(); // value must be finite, not Infinity or -Infinity\nz.number().safe(); // value must be between Number.MIN_SAFE_INTEGER and Number.MAX_SAFE_INTEGER\n```\n\nOptionally, you can pass in a second argument to provide a custom error message.\n\n```ts\nz.number().lte(5, { message: \"this👏is👏too👏big\" });\n```\n\n## BigInts\n\nZod includes a handful of bigint-specific validations.\n\n```ts\nz.bigint().gt(5n);\nz.bigint().gte(5n); // alias `.min(5n)`\nz.bigint().lt(5n);\nz.bigint().lte(5n); // alias `.max(5n)`\n\nz.bigint().positive(); // > 0n\nz.bigint().nonnegative(); // >= 0n\nz.bigint().negative(); // < 0n\nz.bigint().nonpositive(); // <= 0n\n\nz.bigint().multipleOf(5n); // Evenly divisible by 5n.\n```\n\n## NaNs\n\nYou can customize certain error messages when creating a nan schema.\n\n```ts\nconst isNaN = z.nan({\n  required_error: \"isNaN is required\",\n  invalid_type_error: \"isNaN must be 'not a number'\",\n});\n```\n\n## Booleans\n\nYou can customize certain error messages when creating a boolean schema.\n\n```ts\nconst isActive = z.boolean({\n  required_error: \"isActive is required\",\n  invalid_type_error: \"isActive must be a boolean\",\n});\n```\n\n## Dates\n\nUse z.date() to validate `Date` instances.\n\n```ts\nz.date().safeParse(new Date()); // success: true\nz.date().safeParse(\"2022-01-12T00:00:00.000Z\"); // success: false\n```\n\nYou can customize certain error messages when creating a date schema.\n\n```ts\nconst myDateSchema = z.date({\n  required_error: \"Please select a date and time\",\n  invalid_type_error: \"That's not a date!\",\n});\n```\n\nZod provides a handful of date-specific validations.\n\n```ts\nz.date().min(new Date(\"1900-01-01\"), { message: \"Too old\" });\nz.date().max(new Date(), { message: \"Too young!\" });\n```\n\n**Coercion to Date**\n\nSince [zod 3.20](https://github.com/colinhacks/zod/releases/tag/v3.20), use [`z.coerce.date()`](#coercion-for-primitives) to pass the input through `new Date(input)`.\n\n```ts\nconst dateSchema = z.coerce.date();\ntype DateSchema = z.infer<typeof dateSchema>;\n// type DateSchema = Date\n\n/* valid dates */\nconsole.log(dateSchema.safeParse(\"2023-01-10T00:00:00.000Z\").success); // true\nconsole.log(dateSchema.safeParse(\"2023-01-10\").success); // true\nconsole.log(dateSchema.safeParse(\"1/10/23\").success); // true\nconsole.log(dateSchema.safeParse(new Date(\"1/10/23\")).success); // true\n\n/* invalid dates */\nconsole.log(dateSchema.safeParse(\"2023-13-10\").success); // false\nconsole.log(dateSchema.safeParse(\"0000-00-00\").success); // false\n```\n\nFor older zod versions, use [`z.preprocess`](#preprocess) like [described in this thread](https://github.com/colinhacks/zod/discussions/879#discussioncomment-2036276).\n\n## Zod enums\n\n```ts\nconst FishEnum = z.enum([\"Salmon\", \"Tuna\", \"Trout\"]);\ntype FishEnum = z.infer<typeof FishEnum>;\n// 'Salmon' | 'Tuna' | 'Trout'\n```\n\n`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](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html#const-assertions) for details.\n\n```ts\nconst VALUES = [\"Salmon\", \"Tuna\", \"Trout\"] as const;\nconst FishEnum = z.enum(VALUES);\n```\n\nThis is not allowed, since Zod isn't able to infer the exact values of each element.\n\n```ts\nconst fish = [\"Salmon\", \"Tuna\", \"Trout\"];\nconst FishEnum = z.enum(fish);\n```\n\n**`.enum`**\n\nTo get autocompletion with a Zod enum, use the `.enum` property of your schema:\n\n```ts\nFishEnum.enum.Salmon; // => autocompletes\n\nFishEnum.enum;\n/*\n=> {\n  Salmon: \"Salmon\",\n  Tuna: \"Tuna\",\n  Trout: \"Trout\",\n}\n*/\n```\n\nYou can also retrieve the list of options as a tuple with the `.options` property:\n\n```ts\nFishEnum.options; // [\"Salmon\", \"Tuna\", \"Trout\"];\n```\n\n**`.exclude/.extract()`**\n\nYou can create subsets of a Zod enum with the `.exclude` and `.extract` methods.\n\n```ts\nconst FishEnum = z.enum([\"Salmon\", \"Tuna\", \"Trout\"]);\nconst SalmonAndTrout = FishEnum.extract([\"Salmon\", \"Trout\"]);\nconst TunaOnly = FishEnum.exclude([\"Salmon\", \"Trout\"]);\n```\n\n## Native enums\n\nZod 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()`.\n\n**Numeric enums**\n\n```ts\nenum Fruits {\n  Apple,\n  Banana,\n}\n\nconst FruitEnum = z.nativeEnum(Fruits);\ntype FruitEnum = z.infer<typeof FruitEnum>; // Fruits\n\nFruitEnum.parse(Fruits.Apple); // passes\nFruitEnum.parse(Fruits.Banana); // passes\nFruitEnum.parse(0); // passes\nFruitEnum.parse(1); // passes\nFruitEnum.parse(3); // fails\n```\n\n**String enums**\n\n```ts\nenum Fruits {\n  Apple = \"apple\",\n  Banana = \"banana\",\n  Cantaloupe, // you can mix numerical and string enums\n}\n\nconst FruitEnum = z.nativeEnum(Fruits);\ntype FruitEnum = z.infer<typeof FruitEnum>; // Fruits\n\nFruitEnum.parse(Fruits.Apple); // passes\nFruitEnum.parse(Fruits.Cantaloupe); // passes\nFruitEnum.parse(\"apple\"); // passes\nFruitEnum.parse(\"banana\"); // passes\nFruitEnum.parse(0); // passes\nFruitEnum.parse(\"Cantaloupe\"); // fails\n```\n\n**Const enums**\n\nThe `.nativeEnum()` function works for `as const` objects as well. ⚠️ `as const` requires TypeScript 3.4+!\n\n```ts\nconst Fruits = {\n  Apple: \"apple\",\n  Banana: \"banana\",\n  Cantaloupe: 3,\n} as const;\n\nconst FruitEnum = z.nativeEnum(Fruits);\ntype FruitEnum = z.infer<typeof FruitEnum>; // \"apple\" | \"banana\" | 3\n\nFruitEnum.parse(\"apple\"); // passes\nFruitEnum.parse(\"banana\"); // passes\nFruitEnum.parse(3); // passes\nFruitEnum.parse(\"Cantaloupe\"); // fails\n```\n\nYou can access the underlying object with the `.enum` property:\n\n```ts\nFruitEnum.enum.Apple; // \"apple\"\n```\n\n## Optionals\n\nYou can make any schema optional with `z.optional()`. This wraps the schema in a `ZodOptional` instance and returns the result.\n\n```ts\nconst schema = z.optional(z.string());\n\nschema.parse(undefined); // => returns undefined\ntype A = z.infer<typeof schema>; // string | undefined\n```\n\nFor convenience, you can also call the `.optional()` method on an existing schema.\n\n```ts\nconst user = z.object({\n  username: z.string().optional(),\n});\ntype C = z.infer<typeof user>; // { username?: string | undefined };\n```\n\nYou can extract the wrapped schema from a `ZodOptional` instance with `.unwrap()`.\n\n```ts\nconst stringSchema = z.string();\nconst optionalString = stringSchema.optional();\noptionalString.unwrap() === stringSchema; // true\n```\n\n## Nullables\n\nSimilarly, you can create nullable types with `z.nullable()`.\n\n```ts\nconst nullableString = z.nullable(z.string());\nnullableString.parse(\"asdf\"); // => \"asdf\"\nnullableString.parse(null); // => null\n```\n\nOr use the `.nullable()` method.\n\n```ts\nconst E = z.string().nullable(); // equivalent to nullableString\ntype E = z.infer<typeof E>; // string | null\n```\n\nExtract the inner schema with `.unwrap()`.\n\n```ts\nconst stringSchema = z.string();\nconst nullableString = stringSchema.nullable();\nnullableString.unwrap() === stringSchema; // true\n```\n\n## Objects\n\n```ts\n// all properties are required by default\nconst Dog = z.object({\n  name: z.string(),\n  age: z.number(),\n});\n\n// extract the inferred type like this\ntype Dog = z.infer<typeof Dog>;\n\n// equivalent to:\ntype Dog = {\n  name: string;\n  age: number;\n};\n```\n\n### `.shape`\n\nUse `.shape` to access the schemas for a particular key.\n\n```ts\nDog.shape.name; // => string schema\nDog.shape.age; // => number schema\n```\n\n### `.keyof`\n\nUse `.keyof` to create a `ZodEnum` schema from the keys of an object schema.\n\n```ts\nconst keySchema = Dog.keyof();\nkeySchema; // ZodEnum<[\"name\", \"age\"]>\n```\n\n### `.extend`\n\nYou can add additional fields to an object schema with the `.extend` method.\n\n```ts\nconst DogWithBreed = Dog.extend({\n  breed: z.string(),\n});\n```\n\nYou can use `.extend` to overwrite fields! Be careful with this power!\n\n### `.merge`\n\nEquivalent to `A.extend(B.shape)`.\n\n```ts\nconst BaseTeacher = z.object({ students: z.array(z.string()) });\nconst HasID = z.object({ id: z.string() });\n\nconst Teacher = BaseTeacher.merge(HasID);\ntype Teacher = z.infer<typeof Teacher>; // => { students: string[], id: string }\n```\n\n> 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.\n\n### `.pick/.omit`\n\nInspired 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:\n\n```ts\nconst Recipe = z.object({\n  id: z.string(),\n  name: z.string(),\n  ingredients: z.array(z.string()),\n});\n```\n\nTo only keep certain keys, use `.pick` .\n\n```ts\nconst JustTheName = Recipe.pick({ name: true });\ntype JustTheName = z.infer<typeof JustTheName>;\n// => { name: string }\n```\n\nTo remove certain keys, use `.omit` .\n\n```ts\nconst NoIDRecipe = Recipe.omit({ id: true });\n\ntype NoIDRecipe = z.infer<typeof NoIDRecipe>;\n// => { name: string, ingredients: string[] }\n```\n\n### `.partial`\n\nInspired by the built-in TypeScript utility type [Partial](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype), the `.partial` method makes all properties optional.\n\nStarting from this object:\n\n```ts\nconst user = z.object({\n  email: z.string(),\n  username: z.string(),\n});\n// { email: string; username: string }\n```\n\nWe can create a partial version:\n\n```ts\nconst partialUser = user.partial();\n// { email?: string | undefined; username?: string | undefined }\n```\n\nYou can also specify which properties to make optional:\n\n```ts\nconst optionalEmail = user.partial({\n  email: true,\n});\n/*\n{\n  email?: string | undefined;\n  username: string\n}\n*/\n```\n\n### `.deepPartial`\n\nThe `.partial` method is shallow — it only applies one level deep. There is also a \"deep\" version:\n\n```ts\nconst user = z.object({\n  username: z.string(),\n  location: z.object({\n    latitude: z.number(),\n    longitude: z.number(),\n  }),\n  strings: z.array(z.object({ value: z.string() })),\n});\n\nconst deepPartialUser = user.deepPartial();\n\n/*\n{\n  username?: string | undefined,\n  location?: {\n    latitude?: number | undefined;\n    longitude?: number | undefined;\n  } | undefined,\n  strings?: { value?: string}[]\n}\n*/\n```\n\n> Important limitation: deep partials only work as expected in hierarchies of objects, arrays, and tuples.\n\n### `.required`\n\nContrary to the `.partial` method, the `.required` method makes all properties required.\n\nStarting from this object:\n\n```ts\nconst user = z\n  .object({\n    email: z.string(),\n    username: z.string(),\n  })\n  .partial();\n// { email?: string | undefined; username?: string | undefined }\n```\n\nWe can create a required version:\n\n```ts\nconst requiredUser = user.required();\n// { email: string; username: string }\n```\n\nYou can also specify which properties to make required:\n\n```ts\nconst requiredEmail = user.required({\n  email: true,\n});\n/*\n{\n  email: string;\n  username?: string | undefined;\n}\n*/\n```\n\n### `.passthrough`\n\nBy default Zod object schemas strip out unrecognized keys during parsing.\n\n```ts\nconst person = z.object({\n  name: z.string(),\n});\n\nperson.parse({\n  name: \"bob dylan\",\n  extraKey: 61,\n});\n// => { name: \"bob dylan\" }\n// extraKey has been stripped\n```\n\nInstead, if you want to pass through unknown keys, use `.passthrough()` .\n\n```ts\nperson.passthrough().parse({\n  name: \"bob dylan\",\n  extraKey: 61,\n});\n// => { name: \"bob dylan\", extraKey: 61 }\n```\n\n### `.strict`\n\nBy 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.\n\n```ts\nconst person = z\n  .object({\n    name: z.string(),\n  })\n  .strict();\n\nperson.parse({\n  name: \"bob dylan\",\n  extraKey: 61,\n});\n// => throws ZodError\n```\n\n### `.strip`\n\nYou can use the `.strip` method to reset an object schema to the default behavior (stripping unrecognized keys).\n\n### `.catchall`\n\nYou can pass a \"catchall\" schema into an object schema. All unknown keys will be validated against it.\n\n```ts\nconst person = z\n  .object({\n    name: z.string(),\n  })\n  .catchall(z.number());\n\nperson.parse({\n  name: \"bob dylan\",\n  validExtraKey: 61, // works fine\n});\n\nperson.parse({\n  name: \"bob dylan\",\n  validExtraKey: false, // fails\n});\n// => throws ZodError\n```\n\nUsing `.catchall()` obviates `.passthrough()` , `.strip()` , or `.strict()`. All keys are now considered \"known\".\n\n## Arrays\n\n```ts\nconst stringArray = z.array(z.string());\n\n// equivalent\nconst stringArray = z.string().array();\n```\n\nBe careful with the `.array()` method. It returns a new `ZodArray` instance. This means the _order_ in which you call methods matters. For instance:\n\n```ts\nz.string().optional().array(); // (string | undefined)[]\nz.string().array().optional(); // string[] | undefined\n```\n\n### `.element`\n\nUse `.element` to access the schema for an element of the array.\n\n```ts\nstringArray.element; // => string schema\n```\n\n### `.nonempty`\n\nIf you want to ensure that an array contains at least one element, use `.nonempty()`.\n\n```ts\nconst nonEmptyStrings = z.string().array().nonempty();\n// the inferred type is now\n// [string, ...string[]]\n\nnonEmptyStrings.parse([]); // throws: \"Array cannot be empty\"\nnonEmptyStrings.parse([\"Ariana Grande\"]); // passes\n```\n\nYou can optionally specify a custom error message:\n\n```ts\n// optional custom error message\nconst nonEmptyStrings = z.string().array().nonempty({\n  message: \"Can't be empty!\",\n});\n```\n\n### `.min/.max/.length`\n\n```ts\nz.string().array().min(5); // must contain 5 or more items\nz.string().array().max(5); // must contain 5 or fewer items\nz.string().array().length(5); // must contain 5 items exactly\n```\n\nUnlike `.nonempty()` these methods do not change the inferred type.\n\n## Tuples\n\nUnlike arrays, tuples have a fixed number of elements and each element can have a different type.\n\n```ts\nconst athleteSchema = z.tuple([\n  z.string(), // name\n  z.number(), // jersey number\n  z.object({\n    pointsScored: z.number(),\n  }), // statistics\n]);\n\ntype Athlete = z.infer<typeof athleteSchema>;\n// type Athlete = [string, number, { pointsScored: number }]\n```\n\nA variadic (\"rest\") argument can be added with the `.rest` method.\n\n```ts\nconst variadicTuple = z.tuple([z.string()]).rest(z.number());\nconst result = variadicTuple.parse([\"hello\", 1, 2, 3]);\n// => [string, ...number[]];\n```\n\n## Unions\n\nZod includes a built-in `z.union` method for composing \"OR\" types.\n\n```ts\nconst stringOrNumber = z.union([z.string(), z.number()]);\n\nstringOrNumber.parse(\"foo\"); // passes\nstringOrNumber.parse(14); // passes\n```\n\nZod will test the input against each of the \"options\" in order and return the first value that validates successfully.\n\nFor convenience, you can also use the [`.or` method](#or):\n\n```ts\nconst stringOrNumber = z.string().or(z.number());\n```\n\n**Optional string validation:**\n\nTo validate an optional form input, you can union the desired string validation with an empty string [literal](#literals).\n\nThis example validates an input that is optional but needs to contain a [valid URL](#strings):\n\n```ts\nconst optionalUrl = z.union([z.string().url().nullish(), z.literal(\"\")]);\n\nconsole.log(optionalUrl.safeParse(undefined).success); // true\nconsole.log(optionalUrl.safeParse(null).success); // true\nconsole.log(optionalUrl.safeParse(\"\").success); // true\nconsole.log(optionalUrl.safeParse(\"https://zod.dev\").success); // true\nconsole.log(optionalUrl.safeParse(\"not a valid url\").success); // false\n```\n\n## Discriminated unions\n\nA discriminated union is a union of object schemas that all share a particular key.\n\n```ts\ntype MyUnion =\n  | { status: \"success\"; data: string }\n  | { status: \"failed\"; error: Error };\n```\n\nSuch 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) to determine which schema should be used to parse the input. This makes parsing more efficient and lets Zod report friendlier errors.\n\nWith 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\".\n\n```ts\nconst myUnion = z.discriminatedUnion(\"status\", [\n  z.object({ status: z.literal(\"success\"), data: z.string() }),\n  z.object({ status: z.literal(\"failed\"), error: z.instanceof(Error) }),\n]);\n\nmyUnion.parse({ status: \"success\", data: \"yippie ki yay\" });\n```\n\nYou can extract a reference to the array of schemas with the `.options` property.\n\n```ts\nmyUnion.options; // [ZodObject<...>, ZodObject<...>]\n```\n\nTo merge two or more discriminated unions, use `.options` with destructuring.\n\n```ts\nconst A = z.discriminatedUnion(\"status\", [\n  /* options */\n]);\nconst B = z.discriminatedUnion(\"status\", [\n  /* options */\n]);\n\nconst AB = z.discriminatedUnion(\"status\", [...A.options, ...B.options]);\n```\n\n## Records\n\nRecord schemas are used to validate types such as `Record<string, number>`. This is particularly useful for storing or caching items by ID.\n\n<!-- If you want to validate the _values_ of an object against some schema but don't care about the keys, use `z.record(valueType)`:\n\n```ts\nconst NumberCache = z.record(z.number());\n\ntype NumberCache = z.infer<typeof NumberCache>;\n// => { [k: string]: number }\n``` -->\n\n```ts\nconst User = z.object({ name: z.string() });\n\nconst UserStore = z.record(z.string(), User);\ntype UserStore = z.infer<typeof UserStore>;\n// => Record<string, { name: string }>\n```\n\nThe schema and inferred type can be used like so:\n\n```ts\nconst userStore: UserStore = {};\n\nuserStore[\"77d2586b-9e8e-4ecf-8b21-ea7e0530eadd\"] = {\n  name: \"Carlotta\",\n}; // passes\n\nuserStore[\"77d2586b-9e8e-4ecf-8b21-ea7e0530eadd\"] = {\n  whatever: \"Ice cream sundae\",\n}; // TypeError\n```\n\n**A note on numerical keys**\n\nWhile `z.record(keyType, valueType)` is able to accept numerical key types and TypeScript's built-in Record type is `Record<KeyType, ValueType>`, it's hard to represent the TypeScript type `Record<number, any>` in Zod.\n\nAs it turns out, TypeScript's behavior surrounding `[k: number]` is a little unintuitive:\n\n```ts\nconst testMap: { [k: number]: string } = {\n  1: \"one\",\n};\n\nfor (const key in testMap) {\n  console.log(`${key}: ${typeof key}`);\n}\n// prints: `1: string`\n```\n\nAs 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.\n\n## Maps\n\n```ts\nconst stringNumberMap = z.map(z.string(), z.number());\n\ntype StringNumberMap = z.infer<typeof stringNumberMap>;\n// type StringNumberMap = Map<string, number>\n```\n\n## Sets\n\n```ts\nconst numberSet = z.set(z.number());\ntype NumberSet = z.infer<typeof numberSet>;\n// type NumberSet = Set<number>\n```\n\nSet schemas can be further constrained with the following utility methods.\n\n```ts\nz.set(z.string()).nonempty(); // must contain at least one item\nz.set(z.string()).min(5); // must contain 5 or more items\nz.set(z.string()).max(5); // must contain 5 or fewer items\nz.set(z.string()).size(5); // must contain 5 items exactly\n```\n\n## Intersections\n\nIntersections are useful for creating \"logical AND\" types. This is useful for intersecting two object types.\n\n```ts\nconst Person = z.object({\n  name: z.string(),\n});\n\nconst Employee = z.object({\n  role: z.string(),\n});\n\nconst EmployedPerson = z.intersection(Person, Employee);\n\n// equivalent to:\nconst EmployedPerson = Person.and(Employee);\n```\n\nThough 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`.\n\n```ts\nconst a = z.union([z.number(), z.string()]);\nconst b = z.union([z.number(), z.boolean()]);\nconst c = z.intersection(a, b);\n\ntype c = z.infer<typeof c>; // => number\n```\n\n<!-- Intersections in Zod are not smart. Whatever data you pass into `.parse()` gets passed into the two intersected schemas. Because Zod object schemas don't allow any unknown keys by default, there are some unintuitive behavior surrounding intersections of object schemas. -->\n\n<!--\n\n``` ts\nconst A = z.object({\n  a: z.string(),\n});\n\nconst B = z.object({\n  b: z.string(),\n});\n\nconst AB = z.intersection(A, B);\n\ntype Teacher = z.infer<typeof Teacher>;\n// { id:string; name:string };\n```  -->\n\n## Recursive types\n\nYou 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\".\n\n```ts\nconst baseCategorySchema = z.object({\n  name: z.string(),\n});\n\ntype Category = z.infer<typeof baseCategorySchema> & {\n  subcategories: Category[];\n};\n\nconst categorySchema: z.ZodType<Category> = baseCategorySchema.extend({\n  subcategories: z.lazy(() => categorySchema.array()),\n});\n\ncategorySchema.parse({\n  name: \"People\",\n  subcategories: [\n    {\n      name: \"Politicians\",\n      subcategories: [\n        {\n          name: \"Presidents\",\n          subcategories: [],\n        },\n      ],\n    },\n  ],\n}); // passes\n```\n\nThanks to [crasite](https://github.com/crasite) for this example.\n\n### ZodType with ZodEffects\n\nWhen using `z.ZodType` with `z.ZodEffects` (\n[`.refine`](https://github.com/colinhacks/zod#refine),\n[`.transform`](https://github.com/colinhacks/zod#transform),\n[`preprocess`](https://github.com/colinhacks/zod#preprocess),\netc...\n), you will need to define the input and output types of the schema. `z.ZodType<Output, z.ZodTypeDef, Input>`\n\n```ts\nconst isValidId = (id: string): id is `${string}/${string}` =>\n  id.split(\"/\").length === 2;\n\nconst baseSchema = z.object({\n  id: z.string().refine(isValidId),\n});\n\ntype Input = z.input<typeof baseSchema> & {\n  children: Input[];\n};\n\ntype Output = z.output<typeof baseSchema> & {\n  children: Output[];\n};\n\nconst schema: z.ZodType<Output, z.ZodTypeDef, Input> = baseSchema.extend({\n  children: z.lazy(() => schema.array()),\n});\n```\n\nThanks to [marcus13371337](https://github.com/marcus13371337) and [JoelBeeldi](https://github.com/JoelBeeldi) for this example.\n\n### JSON type\n\nIf you want to validate any JSON value, you can use the snippet below.\n\n```ts\nconst literalSchema = z.union([z.string(), z.number(), z.boolean(), z.null()]);\ntype Literal = z.infer<typeof literalSchema>;\ntype Json = Literal | { [key: string]: Json } | Json[];\nconst jsonSchema: z.ZodType<Json> = z.lazy(() =>\n  z.union([literalSchema, z.array(jsonSchema), z.record(jsonSchema)])\n);\n\njsonSchema.parse(data);\n```\n\nThanks to [ggoodman](https://github.com/ggoodman) for suggesting this.\n\n### Cyclical objects\n\nDespite supporting recursive schemas, passing cyclical data into Zod will cause an infinite loop in some cases.\n\n> To detect cyclical objects before they cause problems, consider [this approach](https://gist.github.com/colinhacks/d35825e505e635df27cc950776c5500b).\n\n## Promises\n\n```ts\nconst numberPromise = z.promise(z.number());\n```\n\n\"Parsing\" works a little differently with promise schemas. Validation happens in two parts:\n\n1. Zod synchronously checks that the input is an instance of Promise (i.e. an object with `.then` and `.catch` methods.).\n2. 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.\n\n```ts\nnumberPromise.parse(\"tuna\");\n// ZodError: Non-Promise type: string\n\nnumberPromise.parse(Promise.resolve(\"tuna\"));\n// => Promise<number>\n\nconst test = async () => {\n  await numberPromise.parse(Promise.resolve(\"tuna\"));\n  // ZodError: Non-number type: string\n\n  await numberPromise.parse(Promise.resolve(3.14));\n  // => 3.14\n};\n```\n\n<!-- #### Non-native promise implementations\n\nWhen \"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. -->\n\n## Instanceof\n\nYou 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.\n\n```ts\nclass Test {\n  name: string;\n}\n\nconst TestSchema = z.instanceof(Test);\n\nconst blob: any = \"whatever\";\nTestSchema.parse(new Test()); // passes\nTestSchema.parse(blob); // throws\n```\n\n## Functions\n\nZod 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\".\n\nYou can create a function schema with `z.function(args, returnType)` .\n\n```ts\nconst myFunction = z.function();\n\ntype myFunction = z.infer<typeof myFunction>;\n// => ()=>unknown\n```\n\nDefine inputs and outputs.\n\n```ts\nconst myFunction = z\n  .function()\n  .args(z.string(), z.number()) // accepts an arbitrary number of arguments\n  .returns(z.boolean());\n\ntype myFunction = z.infer<typeof myFunction>;\n// => (arg0: string, arg1: number)=>boolean\n```\n\n<!--\n\n``` ts\nconst args = z.tuple([z.string()]);\n\nconst returnType = z.number();\n\nconst myFunction = z.function(args, returnType);\ntype myFunction = z.infer<typeof myFunction>;\n// => (arg0: string)=>number\n``` -->\n\nFunction schemas have an `.implement()` method which accepts a function and returns a new function that automatically validates its inputs and outputs.\n\n```ts\nconst trimmedLength = z\n  .function()\n  .args(z.string()) // accepts an arbitrary number of arguments\n  .returns(z.number())\n  .implement((x) => {\n    // TypeScript knows x is a string!\n    return x.trim().length;\n  });\n\ntrimmedLength(\"sandwich\"); // => 8\ntrimmedLength(\" asdf \"); // => 4\n```\n\nIf you only care about validating inputs, just don't call the `.returns()` method. The output type will be inferred from the implementation.\n\n> 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.)\n\n```ts\nconst myFunction = z\n  .function()\n  .args(z.string())\n  .implement((arg) => {\n    return [arg.length];\n  });\n\nmyFunction; // (arg: string)=>number[]\n```\n\nExtract the input and output schemas from a function schema.\n\n```ts\nmyFunction.parameters();\n// => ZodTuple<[ZodString, ZodNumber]>\n\nmyFunction.returnType();\n// => ZodBoolean\n```\n\n<!-- `z.function()` accepts two arguments:\n\n* `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([])`).\n* `returnType: any Zod schema` The second argument is the function's return type. This can be any Zod schema. -->\n\n## Preprocess\n\n> Zod now supports primitive coercion without the need for `.preprocess()`. See the [coercion docs](#coercion-for-primitives) for more information.\n\nTypically 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](#transform).)\n\nBut 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()`.\n\n```ts\nconst castToString = z.preprocess((val) => String(val), z.string());\n```\n\nThis returns a `ZodEffects` instance. `ZodEffects` is a wrapper class that contains all logic pertaining to preprocessing, refinements, and transforms.\n\n## Custom schemas\n\nYou can create a Zod schema for any TypeScript type by using `z.custom()`. This is useful for creating schemas for types that are not supported by Zod out of the box, such as template string literals.\n\n```ts\nconst px = z.custom<`${number}px`>((val) => {\n  return typeof val === \"string\" ? /^\\d+px$/.test(val) : false;\n});\n\ntype px = z.infer<typeof px>; // `${number}px`\n\npx.parse(\"42px\"); // \"42px\"\npx.parse(\"42vw\"); // throws;\n```\n\nIf you don't provide a validation function, Zod will allow any value. This can be dangerous!\n\n```ts\nz.custom<{ arg: string }>(); // performs no validation\n```\n\nYou can customize the error message and other options by passing a second argument. This parameter works the same way as the params parameter of [`.refine`](#refine).\n\n```ts\nz.custom<...>((val) => ..., \"custom error message\");\n```\n\n## Schema methods\n\nAll Zod schemas contain certain methods.\n\n### `.parse`\n\n`.parse(data: unknown): T`\n\nGiven 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.\n\n> IMPORTANT: The value returned by `.parse` is a _deep clone_ of the variable you passed in.\n\n```ts\nconst stringSchema = z.string();\n\nstringSchema.parse(\"fish\"); // => returns \"fish\"\nstringSchema.parse(12); // throws error\n```\n\n### `.parseAsync`\n\n`.parseAsync(data:unknown): Promise<T>`\n\nIf you use asynchronous [refinements](#refine) or [transforms](#transform) (more on those later), you'll need to use `.parseAsync`.\n\n```ts\nconst stringSchema = z.string().refine(async (val) => val.length <= 8);\n\nawait stringSchema.parseAsync(\"hello\"); // => returns \"hello\"\nawait stringSchema.parseAsync(\"hello world\"); // => throws error\n```\n\n### `.safeParse`\n\n`.safeParse(data:unknown): { success: true; data: T; } | { success: false; error: ZodError; }`\n\nIf 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.\n\n```ts\nstringSchema.safeParse(12);\n// => { success: false; error: ZodError }\n\nstringSchema.safeParse(\"billie\");\n// => { success: true; data: 'billie' }\n```\n\nThe result is a _discriminated union_, so you can handle errors very conveniently:\n\n```ts\nconst result = stringSchema.safeParse(\"billie\");\nif (!result.success) {\n  // handle error then return\n  result.error;\n} else {\n  // do something\n  result.data;\n}\n```\n\n### `.safeParseAsync`\n\n> Alias: `.spa`\n\nAn asynchronous version of `safeParse`.\n\n```ts\nawait stringSchema.safeParseAsync(\"billie\");\n```\n\nFor convenience, this has been aliased to `.spa`:\n\n```ts\nawait stringSchema.spa(\"billie\");\n```\n\n### `.refine`\n\n`.refine(validator: (data:T)=>any, params?: RefineParams)`\n\nZod lets you provide custom validation logic via _refinements_. (For advanced features like creating multiple issues and customizing error codes, see [`.superRefine`](#superrefine).)\n\nZod 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.\n\nFor example, you can define a custom validation check on _any_ Zod schema with `.refine` :\n\n```ts\nconst myString = z.string().refine((val) => val.length <= 255, {\n  message: \"String can't be more than 255 characters\",\n});\n```\n\n> ⚠️ Refinement functions should not throw. Instead they should return a falsy value to signal failure.\n\n#### Arguments\n\nAs you can see, `.refine` takes two arguments.\n\n1. 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.)\n2. The second argument accepts some options. You can use this to customize certain error-handling behavior:\n\n```ts\ntype RefineParams = {\n  // override error message\n  message?: string;\n\n  // appended to error path\n  path?: (string | number)[];\n\n  // params object you can use to customize message\n  // in error map\n  params?: object;\n};\n```\n\nFor advanced cases, the second argument can also be a function that returns `RefineParams`.\n\n```ts\nconst longString = z.string().refine(\n  (val) => val.length > 10,\n  (val) => ({ message: `${val} is not more than 10 characters` })\n);\n```\n\n#### Customize error path\n\n```ts\nconst passwordForm = z\n  .object({\n    password: z.string(),\n    confirm: z.string(),\n  })\n  .refine((data) => data.password === data.confirm, {\n    message: \"Passwords don't match\",\n    path: [\"confirm\"], // path of error\n  });\n\npasswordForm.parse({ password: \"asdf\", confirm: \"qwer\" });\n```\n\nBecause you provided a `path` parameter, the resulting error will be:\n\n```ts\nZodError {\n  issues: [{\n    \"code\": \"custom\",\n    \"path\": [ \"confirm\" ],\n    \"message\": \"Passwords don't match\"\n  }]\n}\n```\n\n#### Asynchronous refinements\n\nRefinements can also be async:\n\n```ts\nconst userId = z.string().refine(async (id) => {\n  // verify that ID exists in database\n  return true;\n});\n```\n\n> ⚠️ If you use async refinements, you must use the `.parseAsync` method to parse data! Otherwise Zod will throw an error.\n\n#### Relationship to transforms\n\nTransforms and refinements can be interleaved:\n\n```ts\nz.string()\n  .transform((val) => val.length)\n  .refine((val) => val > 25);\n```\n\n<!-- Note that the `path` is set to `[\"confirm\"]` , so you can easily display this error underneath the \"Confirm password\" textbox.\n\n```ts\nconst allForms = z.object({ passwordForm }).parse({\n  passwordForm: {\n    password: \"asdf\",\n    confirm: \"qwer\",\n  },\n});\n```\n\nwould result in\n\n```\n\nZodError {\n  issues: [{\n    \"code\": \"custom\",\n    \"path\": [ \"passwordForm\", \"confirm\" ],\n    \"message\": \"Passwords don't match\"\n  }]\n}\n``` -->\n\n### `.superRefine`\n\nThe `.refine` method is actually syntactic sugar atop a more versatile (and verbose) method called `superRefine`. Here's an example:\n\n```ts\nconst Strings = z.array(z.string()).superRefine((val, ctx) => {\n  if (val.length > 3) {\n    ctx.addIssue({\n      code: z.ZodIssueCode.too_big,\n      maximum: 3,\n      type: \"array\",\n      inclusive: true,\n      message: \"Too many items 😡\",\n    });\n  }\n\n  if (val.length !== new Set(val).size) {\n    ctx.addIssue({\n      code: z.ZodIssueCode.custom,\n      message: `No duplicates allowed.`,\n    });\n  }\n});\n```\n\nYou can add as many issues as you like. If `ctx.addIssue` is _not_ called during the execution of the function, validation passes.\n\nNormally refinements always create issues with a `ZodIssueCode.custom` error code, but with `superRefine` it's possible to throw issues of any `ZodIssueCode`. Each issue code is described in detail in the Error Handling guide: [ERROR_HANDLING.md](ERROR_HANDLING.md).\n\n#### Abort early\n\nBy 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`.\n\n```ts\nconst schema = z.number().superRefine((val, ctx) => {\n  if (val < 10) {\n    ctx.addIssue({\n      code: z.ZodIssueCode.custom,\n      message: \"should be >= 10\",\n      fatal: true,\n    });\n\n    return z.NEVER;\n  }\n\n  if (val !== 12) {\n    ctx.addIssue({\n      code: z.ZodIssueCode.custom,\n      message: \"should be twelve\",\n    });\n  }\n});\n```\n\n#### Type refinements\n\nIf you provide a [type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) to `.refine()` or `.superRefine()`, the resulting type will be narrowed down to your predicate's type. This is useful if you are mixing multiple chained refinements and transformations:\n\n```ts\nconst schema = z\n  .object({\n    first: z.string(),\n    second: z.number(),\n  })\n  .nullable()\n  .superRefine((arg, ctx): arg is { first: string; second: number } => {\n    if (!arg) {\n      ctx.addIssue({\n        code: z.ZodIssueCode.custom, // customize your issue\n        message: \"object should exist\",\n      });\n    }\n\n    return z.NEVER; // The return value is not used, but we need to return something to satisfy the typing\n  })\n  // here, TS knows that arg is not null\n  .refine((arg) => arg.first === \"bob\", \"`first` is not `bob`!\");\n```\n\n> ⚠️ You **must** use `ctx.addIssue()` instead of returning a boolean value to indicate whether the validation passes. If `ctx.addIssue` is _not_ called during the execution of the function, validation passes.\n\n### `.transform`\n\nTo transform data after parsing, use the `transform` method.\n\n```ts\nconst stringToNumber = z.string().transform((val) => val.length);\n\nstringToNumber.parse(\"string\"); // => 6\n```\n\n#### Chaining order\n\nNote 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.\n\n```ts\nconst emailToDomain = z\n  .string()\n  .email()\n  .transform((val) => val.split(\"@\")[1]);\n\nemailToDomain.parse(\"colinhacks@example.com\"); // => example.com\n```\n\n#### Validating during transform\n\nThe `.transform` method can simultaneously validate and transform the value. This is often simpler and less duplicative than chaining `transform` and `refine`.\n\nAs with `.superRefine`, the transform function receives a `ctx` object with an `addIssue` method that can be used to register validation issues.\n\n```ts\nconst numberInString = z.string().transform((val, ctx) => {\n  const parsed = parseInt(val);\n  if (isNaN(parsed)) {\n    ctx.addIssue({\n      code: z.ZodIssueCode.custom,\n      message: \"Not a number\",\n    });\n\n    // This is a special symbol you can use to\n    // return early from the transform function.\n    // It has type `never` so it does not affect the\n    // inferred return type.\n    return z.NEVER;\n  }\n  return parsed;\n});\n```\n\n#### Relationship to refinements\n\nTransforms and refinements can be interleaved. These will be executed in the order they are declared.\n\n```ts\nconst nameToGreeting = z\n  .string()\n  .transform((val) => val.toUpperCase())\n  .refine((val) => val.length > 15)\n  .transform((val) => `Hello ${val}`)\n  .refine((val) => val.indexOf(\"!\") === -1);\n```\n\n#### Async transforms\n\nTransforms can also be async.\n\n```ts\nconst IdToUser = z\n  .string()\n  .uuid()\n  .transform(async (id) => {\n    return await getUserById(id);\n  });\n```\n\n> ⚠️ If your schema contains asynchronous transforms, you must use .parseAsync() or .safeParseAsync() to parse data. Otherwise Zod will throw an error.\n\n### `.default`\n\nYou can use transforms to implement the concept of \"default values\" in Zod.\n\n```ts\nconst stringWithDefault = z.string().default(\"tuna\");\n\nstringWithDefault.parse(undefined); // => \"tuna\"\n```\n\nOptionally, you can pass a function into `.default` that will be re-executed whenever a default value needs to be generated:\n\n```ts\nconst numberWithRandomDefault = z.number().default(Math.random);\n\nnumberWithRandomDefault.parse(undefined); // => 0.4413456736055323\nnumberWithRandomDefault.parse(undefined); // => 0.1871840107401901\nnumberWithRandomDefault.parse(undefined); // => 0.7223408162401552\n```\n\nConceptually, this is how Zod processes default values:\n\n1. If the input is `undefined`, the default value is returned\n2. Otherwise, the data is parsed using the base schema\n\n### `.describe`\n\nUse `.describe()` to add a `description` property to the resulting schema.\n\n```ts\nconst documentedString = z\n  .string()\n  .describe(\"A useful bit of text, if you know what to do with it.\");\ndocumentedString.description; // A useful bit of text…\n```\n\nThis can be useful for documenting a field, for example in a JSON Schema using a library like [`zod-to-json-schema`](https://github.com/StefanTerdell/zod-to-json-schema)).\n\n### `.catch`\n\nUse `.catch()` to provide a \"catch value\" to be returned in the event of a parsing error.\n\n```ts\nconst numberWithCatch = z.number().catch(42);\n\nnumberWithCatch.parse(5); // => 5\nnumberWithCatch.parse(\"tuna\"); // => 42\n```\n\nOptionally, you can pass a function into `.catch` that will be re-executed whenever a default value needs to be generated. A `ctx` object containing the caught error will be passed into this function.\n\n```ts\nconst numberWithRandomCatch = z.number().catch((ctx) => {\n  ctx.error; // the caught ZodError\n  return Math.random();\n});\n\nnumberWithRandomCatch.parse(\"sup\"); // => 0.4413456736055323\nnumberWithRandomCatch.parse(\"sup\"); // => 0.1871840107401901\nnumberWithRandomCatch.parse(\"sup\"); // => 0.7223408162401552\n```\n\nConceptually, this is how Zod processes \"catch values\":\n\n1. The data is parsed using the base schema\n2. If the parsing fails, the \"catch value\" is returned\n\n### `.optional`\n\nA convenience method that returns an optional version of a schema.\n\n```ts\nconst optionalString = z.string().optional(); // string | undefined\n\n// equivalent to\nz.optional(z.string());\n```\n\n### `.nullable`\n\nA convenience method that returns a nullable version of a schema.\n\n```ts\nconst nullableString = z.string().nullable(); // string | null\n\n// equivalent to\nz.nullable(z.string());\n```\n\n### `.nullish`\n\nA 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](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#nullish-coalescing).\n\n```ts\nconst nullishString = z.string().nullish(); // string | null | undefined\n\n// equivalent to\nz.string().nullable().optional();\n```\n\n### `.array`\n\nA convenience method that returns an array schema for the given type:\n\n```ts\nconst stringArray = z.string().array(); // string[]\n\n// equivalent to\nz.array(z.string());\n```\n\n### `.promise`\n\nA convenience method for promise types:\n\n```ts\nconst stringPromise = z.string().promise(); // Promise<string>\n\n// equivalent to\nz.promise(z.string());\n```\n\n### `.or`\n\nA convenience method for [union types](#unions).\n\n```ts\nconst stringOrNumber = z.string().or(z.number()); // string | number\n\n// equivalent to\nz.union([z.string(), z.number()]);\n```\n\n### `.and`\n\nA convenience method for creating intersection types.\n\n```ts\nconst nameAndAge = z\n  .object({ name: z.string() })\n  .and(z.object({ age: z.number() })); // { name: string } & { age: number }\n\n// equivalent to\nz.intersection(z.object({ name: z.string() }), z.object({ age: z.number() }));\n```\n\n### `.brand`\n\n`.brand<T>() => ZodBranded<this, B>`\n\nTypeScript's type system is structural, which means that any two types that are structurally equivalent are considered the same.\n\n```ts\ntype Cat = { name: string };\ntype Dog = { name: string };\n\nconst petCat = (cat: Cat) => {};\nconst fido: Dog = { name: \"fido\" };\npetCat(fido); // works fine\n```\n\nIn 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_).\n\n```ts\nconst Cat = z.object({ name: z.string() }).brand<\"Cat\">();\ntype Cat = z.infer<typeof Cat>;\n\nconst petCat = (cat: Cat) => {};\n\n// this works\nconst simba = Cat.parse({ name: \"simba\" });\npetCat(simba);\n\n// this doesn't\npetCat({ name: \"fido\" });\n```\n\nUnder 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.\n\n```ts\nconst Cat = z.object({ name: z.string() }).brand<\"Cat\">();\ntype Cat = z.infer<typeof Cat>;\n// {name: string} & {[symbol]: \"Cat\"}\n```\n\nNote that branded types do not affect the runtime result of `.parse`. It is a static-only construct.\n\n### `.readonly`\n\n`.readonly() => ZodReadonly<this>`\n\nThis method returns a `ZodReadonly` schema instance that parses the input using the base schema, then calls `Object.freeze()` on the result. The inferred type is also marked as `readonly`.\n\n```ts\nconst schema = z.object({ name: z.string() }).readonly();\ntype schema = z.infer<typeof schema>;\n// Readonly<{name: string}>\n\nconst result = schema.parse({ name: \"fido\" });\nresult.name = \"simba\"; // error\n```\n\nThe inferred type uses TypeScript's built-in readonly types when relevant.\n\n```ts\nz.array(z.string()).readonly();\n// readonly string[]\n\nz.tuple([z.string(), z.number()]).readonly();\n// readonly [string, number]\n\nz.map(z.string(), z.date()).readonly();\n// ReadonlyMap<string, Date>\n\nz.set(z.string()).readonly();\n// ReadonlySet<string>\n```\n\n### `.pipe`\n\nSchemas can be chained into validation \"pipelines\". It's useful for easily validating the result after a `.transform()`:\n\n```ts\nz.string()\n  .transform((val) => val.length)\n  .pipe(z.number().min(5));\n```\n\nThe `.pipe()` method returns a `ZodPipeline` instance.\n\n#### You can use `.pipe()` to fix common issues with `z.coerce`.\n\nYou can constrain the input to types that work well with your chosen coercion. Then use `.pipe()` to apply the coercion.\n\nwithout constrained input:\n\n```ts\nconst toDate = z.coerce.date();\n\n// works intuitively\nconsole.log(toDate.safeParse(\"2023-01-01\").success); // true\n\n// might not be what you want\nconsole.log(toDate.safeParse(null).success); // true\n```\n\nwith constrained input:\n\n```ts\nconst datelike = z.union([z.number(), z.string(), z.date()]);\nconst datelikeToDate = datelike.pipe(z.coerce.date());\n\n// still works intuitively\nconsole.log(datelikeToDate.safeParse(\"2023-01-01\").success); // true\n\n// more likely what you want\nconsole.log(datelikeToDate.safeParse(null).success); // false\n```\n\nYou can also use this technique to avoid coercions that throw uncaught errors.\n\nwithout constrained input:\n\n```ts\nconst toBigInt = z.coerce.bigint();\n\n// works intuitively\nconsole.log(toBigInt.safeParse(\"42\")); // true\n\n// probably not what you want\nconsole.log(toBigInt.safeParse(null)); // throws uncaught error\n```\n\nwith constrained input:\n\n```ts\nconst toNumber = z.number().or(z.string()).pipe(z.coerce.number());\nconst toBigInt = z.bigint().or(toNumber).pipe(z.coerce.bigint());\n\n// still works intuitively\nconsole.log(toBigInt.safeParse(\"42\").success); // true\n\n// error handled by zod, more likely what you want\nconsole.log(toBigInt.safeParse(null).success); // false\n```\n\n## Guides and concepts\n\n### Type inference\n\nYou can extract the TypeScript type of any schema with `z.infer<typeof mySchema>` .\n\n```ts\nconst A = z.string();\ntype A = z.infer<typeof A>; // string\n\nconst u: A = 12; // TypeError\nconst u: A = \"asdf\"; // compiles\n```\n\n**What about transforms?**\n\nIn 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`.\n\nYou can separately extract the input and output types like so:\n\n```ts\nconst stringToNumber = z.string().transform((val) => val.length);\n\n// ⚠️ Important: z.infer returns the OUTPUT type!\ntype input = z.input<typeof stringToNumber>; // string\ntype output = z.output<typeof stringToNumber>; // number\n\n// equivalent to z.output!\ntype inferred = z.infer<typeof stringToNumber>; // number\n```\n\n### Writing generic functions\n\nWith TypeScript generics, you can write reusable functions that accept Zod schemas as parameters. This enables you to create custom validation logic, schema transformations, and more, while maintaining type safety and inference.\n\nWhen attempting to write a function that accepts a Zod schema as an input, it's tempting to try something like this:\n\n```ts\nfunction inferSchema<T>(schema: z.ZodType<T>) {\n  return schema;\n}\n```\n\nThis approach is incorrect, and limits TypeScript's ability to properly infer the argument. No matter what you pass in, the type of `schema` will be an instance of `ZodType`.\n\n```ts\ninferSchema(z.string());\n// => ZodType<string>\n```\n\nThis approach loses type information, namely _which subclass_ the input actually is (in this case, `ZodString`). That means you can't call any string-specific methods like `.min()` on the result of `inferSchema`.\n\nA better approach is to infer _the schema as a whole_ instead of merely its inferred type. You can do this with a utility type called `z.ZodTypeAny`.\n\n```ts\nfunction inferSchema<T extends z.ZodTypeAny>(schema: T) {\n  return schema;\n}\n\ninferSchema(z.string());\n// => ZodString\n```\n\n> `ZodTypeAny` is just a shorthand for `ZodType<any, any, any>`, a type that is broad enough to match any Zod schema.\n\nThe Result is now fully and properly typed, and the type system can infer the specific subclass of the schema.\n\n#### Inferring the inferred type\n\nIf you follow the best practice of using `z.ZodTypeAny` as the generic parameter for your schema, you may encounter issues with the parsed data being typed as `any` instead of the inferred type of the schema.\n\n```ts\nfunction parseData<T extends z.ZodTypeAny>(data: unknown, schema: T) {\n  return schema.parse(data);\n}\n\nparseData(\"sup\", z.string());\n// => any\n```\n\nDue to how TypeScript inference works, it is treating `schema` like a `ZodTypeAny` instead of the inferred type. You can fix this with a type cast using `z.infer`.\n\n```ts\nfunction parseData<T extends z.ZodTypeAny>(data: unknown, schema: T) {\n  return schema.parse(data) as z.infer<T>;\n  //                        ^^^^^^^^^^^^^^ <- add this\n}\n\nparseData(\"sup\", z.string());\n// => string\n```\n\n#### Constraining allowable inputs\n\nThe `ZodType` class has three generic parameters.\n\n```ts\nclass ZodType<\n  Output = any,\n  Def extends ZodTypeDef = ZodTypeDef,\n  Input = Output\n> { ... }\n```\n\nBy constraining these in your generic input, you can limit what schemas are allowable as inputs to your function:\n\n```ts\nfunction makeSchemaOptional<T extends z.ZodType<string>>(schema: T) {\n  return schema.optional();\n}\n\nmakeSchemaOptional(z.string());\n// works fine\n\nmakeSchemaOptional(z.number());\n// Error: 'ZodNumber' is not assignable to parameter of type 'ZodType<string, ZodTypeDef, string>'\n```\n\n### Error handling\n\nZod provides a subclass of Error called `ZodError`. ZodErrors contain an `issues` array containing detailed information about the validation problems.\n\n```ts\nconst result = z\n  .object({\n    name: z.string(),\n  })\n  .safeParse({ name: 12 });\n\nif (!result.success) {\n  result.error.issues;\n  /* [\n      {\n        \"code\": \"invalid_type\",\n        \"expected\": \"string\",\n        \"received\": \"number\",\n        \"path\": [ \"name\" ],\n        \"message\": \"Expected string, received number\"\n      }\n  ] */\n}\n```\n\n> For detailed information about the possible error codes and how to customize error messages, check out the dedicated error handling guide: [ERROR_HANDLING.md](ERROR_HANDLING.md)\n\nZod's error reporting emphasizes _completeness_ and _correctness_. If you are looking to present a useful error message to the end user, you should either override Zod's error messages using an error map (described in detail in the Error Handling guide) or use a third-party library like [`zod-validation-error`](https://github.com/causaly/zod-validation-error)\n\n### Error formatting\n\nYou can use the `.format()` method to convert this error into a nested object.\n\n```ts\nconst result = z\n  .object({\n    name: z.string(),\n  })\n  .safeParse({ name: 12 });\n\nif (!result.success) {\n  const formatted = result.error.format();\n  /* {\n    name: { _errors: [ 'Expected string, received number' ] }\n  } */\n\n  formatted.name?._errors;\n  // => [\"Expected string, received number\"]\n}\n```\n\n## Comparison\n\nThere are a handful of other widely-used validation libraries, but all of them have certain design limitations that make for a non-ideal developer experience.\n\n<!-- The table below summarizes the feature differences. Below the table there are more involved discussions of certain alternatives, where necessary. -->\n\n<!-- | Feature                                                                                                                | [Zod](https://github.com/colinhacks) | [Joi](https://github.com/hapijs/joi) | [Yup](https://github.com/jquense/yup) | [io-ts](https://github.com/gcanti/io-ts) | [Runtypes](https://github.com/pelotom/runtypes) | [ow](https://github.com/sindresorhus/ow) | [class-validator](https://github.com/typestack/class-validator) |\n| ---------------------------------------------------------------------------------------------------------------------- | :-----------------------------: | :----------------------------------: | :-----------------------------------: | :--------------------------------------: | :---------------------------------------------: | :--------------------------------------: | :-------------------------------------------------------------: |\n| <abbr title='Any ability to extract a TypeScript type from a validator instance counts.'>Type inference</abbr>         |               🟢                |                  🔴                  |                  🟢                   |                    🟢                    |                       🟢                        |                    🟢                    |                               🟢                                |\n| <abbr title=\"Yup's inferred types are incorrect in certain cases, see discussion below.\">Correct type inference</abbr> |               🟢                |                  🔴                  |                  🔴                   |                    🟢                    |                       🟢                        |                    🟢                    |                               🟢                                |\n\n<abbr title=\"number, string, boolean, null, undefined\">Primitive Types</abbr>\n<abbr title=\"Includes any checks beyond 'Is this a string?', e.g. min/max length, isEmail, isURL, case checking, etc.\">String Validation</abbr>\n<abbr title=\"Includes any checks beyond 'Is this a number?', e.g. min/max, isPositive, integer vs float, etc.\">Number Validation</abbr>\nDates\n\nPrimitive Literals\nObject Literals\nTuple Literals\nObjects\nArrays\nNon-empty arrays\nUnions\nOptionals\nNullable\nEnums\nEnum Autocomplete\nIntersections\nObject Merging\nTuples\nRecursive Types\nFunction Schemas\n\n<abbr title=\"For instance, Yup allows custom error messages with the syntax yup.number().min(5, 'Number must be more than 5!')\">Validation Messages</abbr>\nImmutable instances\nType Guards\nValidity Checking\nCasting\nDefault Values\nRich Errors\nBranded -->\n\n<!-- - Missing object methods: (pick, omit, partial, deepPartial, merge, extend)\n\n* Missing nonempty arrays with proper typing (`[T, ...T[]]`)\n* Missing lazy/recursive types\n* Missing promise schemas\n* Missing function schemas\n* Missing union & intersection schemas\n* Missing support for parsing cyclical data (maybe)\n* Missing error customization -->\n\n### Joi\n\n[https://github.com/hapijs/joi](https://github.com/hapijs/joi)\n\nDoesn't support static type inference 😕\n\n### Yup\n\n[https://github.com/jquense/yup](https://github.com/jquense/yup)\n\nYup is a full-featured library that was implemented first in vanilla JS, and later rewritten in TypeScript.\n\n- Supports casting and transforms\n- All object fields are optional by default\n<!-- - Missing nonempty arrays with proper typing (`[T, ...T[]]`) -->\n- Missing promise schemas\n- Missing function schemas\n- Missing union & intersection schemas\n\n<!-- ¹Yup has a strange interpretation of the word `required`. Instead of meaning \"not undefined\", Yup uses it to mean \"not empty\". So `yup.string().required()` will not accept an empty string, and `yup.array(yup.string()).required()` will not accept an empty array. Instead, Yup us Zod arrays there is a dedicated `.nonempty()` method to indicate this, or you can implement it with a custom refinement. -->\n\n### io-ts\n\n[https://github.com/gcanti/io-ts](https://github.com/gcanti/io-ts)\n\nio-ts is an excellent library by gcanti. The API of io-ts heavily inspired the design of Zod.\n\nIn our experience, io-ts prioritizes functional programming purity over developer experience in many cases. This is a valid and admirable design goal, but it makes io-ts particularly hard to integrate into an existing codebase with a more procedural or object-oriented bias. For instance, consider how to define an object with optional properties in io-ts:\n\n```ts\nimport * as t from \"io-ts\";\n\nconst A = t.type({\n  foo: t.string,\n});\n\nconst B = t.partial({\n  bar: t.number,\n});\n\nconst C = t.intersection([A, B]);\n\ntype C = t.TypeOf<typeof C>;\n// returns { foo: string; bar?: number | undefined }\n```\n\nYou must define the required and optional props in separate object validators, pass the optionals through `t.partial` (which marks all properties as optional), then combine them with `t.intersection` .\n\nConsider the equivalent in Zod:\n\n```ts\nconst C = z.object({\n  foo: z.string(),\n  bar: z.number().optional(),\n});\n\ntype C = z.infer<typeof C>;\n// returns { foo: string; bar?: number | undefined }\n```\n\nThis more declarative API makes schema definitions vastly more concise.\n\n`io-ts` also requires the use of gcanti's functional programming library `fp-ts` to parse results and handle errors. This is another fantastic resource for developers looking to keep their codebase strictly functional. But depending on `fp-ts` necessarily comes with a lot of intellectual overhead; a developer has to be familiar with functional programming concepts and the `fp-ts` nomenclature to use the library.\n\n- Supports codecs with serialization & deserialization transforms\n- Supports branded types\n- Supports advanced functional programming, higher-kinded types, `fp-ts` compatibility\n- Missing object methods: (pick, omit, partial, deepPartial, merge, extend)\n- Missing nonempty arrays with proper typing (`[T, ...T[]]`)\n- Missing promise schemas\n- Missing function schemas\n\n### Runtypes\n\n[https://github.com/pelotom/runtypes](https://github.com/pelotom/runtypes)\n\nGood type inference support.\n\n- Supports \"pattern matching\": computed properties that distribute over unions\n- Missing object methods: (deepPartial, merge)\n- Missing nonempty arrays with proper typing (`[T, ...T[]]`)\n- Missing promise schemas\n- Missing error customization\n\n### Ow\n\n[https://github.com/sindresorhus/ow](https://github.com/sindresorhus/ow)\n\nOw is focused on function input validation. It's a library that makes it easy to express complicated assert statements, but it doesn't let you parse untyped data. They support a much wider variety of types; Zod has a nearly one-to-one mapping with TypeScript's type system, whereas ow lets you validate several highly-specific types out of the box (e.g. `int32Array` , see full list in their README).\n\nIf you want to validate function inputs, use function schemas in Zod! It's a much simpler approach that lets you reuse a function type declaration without repeating yourself (namely, copy-pasting a bunch of ow assertions at the beginning of every function). Also Zod lets you validate your return types as well, so you can be sure there won't be any unexpected data passed downstream.\n\n## Changelog\n\nView the changelog at [CHANGELOG.md](CHANGELOG.md)\n","readmeFilename":"README.md","gitHead":"4641f434f3bb3dab1bb8cb07f44dd2693c72e35e","_nodeVersion":"20.15.0","_npmVersion":"10.7.0","dist":{"integrity":"sha512-7cNGVqhVWHEmri9clARJ2x+jtnrdhrVRoCVw+cRYZ7AHg2XCRp/tzCxQRL3nCJzkBsIamPGLZSVkpWPtTYZHSA==","shasum":"6a25ccd14d33b0aedadc92e582433400326d69df","tarball":"http://registry-npm.ywwl.com/zod/download/zod-3.24.0-canary.20240701T200529.tgz","fileCount":50,"unpackedSize":669759,"attestations":{"url":"https://registry.npmjs.org/-/npm/v1/attestations/zod@3.24.0-canary.20240701T200529","provenance":{"predicateType":"https://slsa.dev/provenance/v1"}},"signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIAepXGQdhMqHWTgLhqDWiO9AFHkzznc/99hu2JFlY02AAiBYLQvf859LWK0UKSlYENqXFlMJo6HXSxCV68o4lW1wAw=="}],"size":116743,"noattachment":false,"key":"/zod/-/zod-3.24.0-canary.20240701T200529.tgz"},"_npmUser":{"name":"colinmcd94","email":"colin@colinhacks.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/zod_3.24.0-canary.20240701T200529_1719864335815_0.31385237031697844"},"_hasShrinkwrap":false,"publish_time":1719864335959,"maintainers":[{"name":"colinmcd94","email":"colin@colinhacks.com"},{"name":"vriad","email":"colin@vriad.com"}],"_cnpm_publish_time":1719864335959,"dist-tags":{"alpha":"3.25.68-alpha.11","beta":"4.1.13-beta.0","canary":"4.5.0-canary.20260828T171753","latest":"4.6.7","next":"3.25.0-beta.20250519T094321"}}