Cannot Read Property 'match' of Undefined Npm
Zod
These docs have been translated into Chinese.
Table of contents
The full documentation is available both on the official documentation site (recommended) and in README.md
.
Become to zod.js.org >>
- What is Zod
- Installation
- Ecosystem
- Basic usage
- Defining schemas
- Primitives
- Literals
- Strings
- Numbers
- NaNs
- Booleans
- Dates
- Zod enums
- Native enums
- Optionals
- Nullables
- Objects
- .shape
- .extend
- .merge
- .pick/.omit
- .partial
- .deepPartial
- .passthrough
- .strict
- .strip
- .catchall
- Arrays
- .chemical element
- .nonempty
- .min/.max/.length
- Tuples
- Records
- Maps
- Sets
- Unions
- Discriminated Unions
- Recursive types
- JSON blazon
- Cyclical data
- Promises
- Instanceof
- Role schemas
- Preprocess
- Schema methods
- .parse
- .parseAsync
- .safeParse
- .safeParseAsync
- .refine
- .superRefine
- .transform
- .default
- .optional
- .nullable
- .nullish
- .array
- .promise
- .or
- .and
- Type inference
- Errors
- Comparing
- Joi
- Yup
- io-ts
- Runtypes
- Changelog
What is Zod
Zod is a TypeScript-commencement schema declaration and validation library. I'1000 using the term "schema" to broadly refer to any information blazon, from a unproblematic string
to a circuitous nested object.
Zod is designed to be as developer-friendly as possible. The goal is to eliminate duplicative type declarations. With Zod, y'all declare a validator once and Zod will automatically infer the static TypeScript type. Information technology'due south piece of cake to compose simpler types into complex data structures.
Some other bang-up aspects:
- Nix dependencies
- Works in Node.js and browsers (including IE eleven)
- Tiny: 8kb minified + zipped
- Immutable: methods (i.e.
.optional()
) return a new example - Concise, chainable interface
- Functional approach: parse, don't validate
- Works with patently JavaScript as well! You don't need to use TypeScript.
Sponsorship
Sponsorship at whatsoever level is appreciated and encouraged. Zod is maintained by a solo programmer (hi!). For private developers, consider the Cup of Coffee tier. If you congenital a paid production using Zod, consider the Startup tier. Yous can learn more about the tiers at github.com/sponsors/colinhacks.
Sponsors
To get your proper noun + Twitter + website here, sponsor Zod at the Freelancer or Consultancy tier.
Installation
To install Zod v3:
strict
manner in your tsconfig.json
. This is a all-time practice for all TypeScript projects.
// tsconfig.json { // ... "compilerOptions": { // ... "strict": true } }
TypeScript requirements
- Zod three.x requires TypeScript 4.1+
- Zod two.ten requires TypeScript three.7+
- Zod one.x requires TypeScript 3.3+
Ecosystem
At that place are a growing number of tools that are congenital atop or support Zod natively! If you've built a tool or library on superlative of Zod, tell me about it on Twitter or outset a Discussion. I'll add it below and tweet it out.
-
tRPC
: Build end-to-finish typesafe APIs without GraphQL. -
ts-to-zod
: Convert TypeScript definitions into Zod schemas. -
zod-to-ts
: Generate TypeScript definitions from Zod schemas. -
@anatine/zod-openapi
: Converts a Zod schema to an OpenAPI v3.10SchemaObject
. -
@anatine/zod-mock
: Generate mock data from a Zod schema. Powered by faker.js. -
@anatine/zod-nestjs
: Helper methods for using Zod in a NestJS projection. -
zod-mocking
: Generate mock information from your Zod schemas. -
zod-fast-bank check
: Generatefast-check
arbitraries from Zod schemas. -
zod-endpoints
: Contract-first strictly typed endpoints with Zod. OpenAPI compatible. -
express-zod-api
: Build Express-based APIs with I/O schema validation and custom middlewares. -
zod-to-json-schema
: Catechumen your Zod schemas into JSON Schemas. -
json-schema-to-zod
: Convert your JSON Schemas into Zod schemas. Use it alive hither. -
json-to-zod
: Catechumen JSON objects into Zod schemas. Utilise it alive here. -
zod-dto
: Generate Nest.js DTOs from a Zod schema. -
soly
: Create CLI applications with zod. -
graphql-codegen-typescript-validation-schema
: GraphQL Code Generator plugin to generate form validation schema from your GraphQL schema -
zod-prisma
: Generate Zod schemas from your Prisma schema.
Class integrations
-
react-hook-class
: A starting time-party Zod resolver for React Hook Course -
zod-formik-adapter
: A community-maintained Formik adapter for Zod
Basic usage
Creating a simple string schema
import { z } from "zod" ; // creating a schema for strings const mySchema = z . string ( ) ; // parsing mySchema . parse ( "tuna" ) ; // => "tuna" mySchema . parse ( 12 ) ; // => throws ZodError // "rubber" parsing (doesn't throw error if validation fails) mySchema . safeParse ( "tuna" ) ; // => { success: true; information: "tuna" } mySchema . safeParse ( 12 ) ; // => { success: false; error: ZodError }
Creating an object schema
import { z } from "zod" ; const User = z . object ( { username: z . string ( ) , } ) ; User . parse ( { username: "Ludwig" } ) ; // excerpt the inferred type blazon User = z . infer < typeof User > ; // { username: cord }
Defining schemas
Primitives
import { z } from "zod" ; // primitive values z . string ( ) ; z . number ( ) ; z . bigint ( ) ; z . boolean ( ) ; z . date ( ) ; // empty types z . undefined ( ) ; z . goose egg ( ) ; z . void ( ) ; // accepts undefined // take hold of-all types // allows any value z . whatever ( ) ; z . unknown ( ) ; // never blazon // allows no values z . never ( ) ;
Literals
const tuna = z . literal ( "tuna" ) ; const twelve = z . literal ( 12 ) ; const tru = z . literal ( true ) ; // retrieve literal value tuna . value ; // "tuna"
Currently there is no support for Engagement or bigint literals in Zod. If y'all have a use case for this feature, please file an consequence.
Strings
Zod includes a handful of string-specific validations.
z . string ( ) . max ( 5 ) ; z . string ( ) . min ( 5 ) ; z . string ( ) . length ( five ) ; z . string ( ) . email ( ) ; z . cord ( ) . url ( ) ; z . string ( ) . uuid ( ) ; z . string ( ) . cuid ( ) ; z . string ( ) . regex ( regex ) ; // deprecated, equivalent to .min(one) z . cord ( ) . nonempty ( ) ; // optional custom error message z . string ( ) . nonempty ( { message: "Can't be empty" } ) ;
Bank check out validator.js for a bunch of other useful string validation functions.
Custom fault messages
You tin customize sure errors when creating a cord schema.
const name = z . cord ( { required_error: "Name is required" , invalid_type_error: "Name must be a string" , } ) ;
When using validation methods, you can pass in an additional argument to provide a custom error message.
z . string ( ) . min ( 5 , { message: "Must be 5 or more characters long" } ) ; z . string ( ) . max ( 5 , { bulletin: "Must exist 5 or fewer characters long" } ) ; z . string ( ) . length ( 5 , { message: "Must be exactly 5 characters long" } ) ; z . cord ( ) . email ( { bulletin: "Invalid email accost" } ) ; z . string ( ) . url ( { message: "Invalid url" } ) ; z . string ( ) . uuid ( { message: "Invalid UUID" } ) ;
Numbers
You lot tin can customize certain error messages when creating a number schema.
const age = z . number ( { required_error: "Historic period is required" , invalid_type_error: "Age must exist a number" , } ) ;
Zod includes a scattering of number-specific validations.
z . number ( ) . gt ( v ) ; z . number ( ) . gte ( five ) ; // alias .min(5) z . number ( ) . lt ( five ) ; z . number ( ) . lte ( v ) ; // alias .max(5) z . number ( ) . int ( ) ; // value must be an integer z . number ( ) . positive ( ) ; // > 0 z . number ( ) . nonnegative ( ) ; // >= 0 z . number ( ) . negative ( ) ; // < 0 z . number ( ) . nonpositive ( ) ; // <= 0 z . number ( ) . multipleOf ( 5 ) ; // Evenly divisible by 5. Alias .stride(5)
Optionally, you can pass in a second argument to provide a custom error message.
z . number ( ) . lte ( 5 , { bulletin: "this👏is👏as well👏large" } ) ;
NaNs
You can customize certain fault messages when creating a nan schema.
const isNaN = z . nan ( { required_error: "isNaN is required" , invalid_type_error: "isNaN must exist not a number" , } ) ;
Booleans
You can customize certain mistake messages when creating a boolean schema.
const isActive = z . boolean ( { required_error: "isActive is required" , invalid_type_error: "isActive must be a boolean" , } ) ;
Dates
z.date() accepts a engagement, non a date string
z . date ( ) . safeParse ( new Date ( ) ) ; // success: truthful z . date ( ) . safeParse ( "2022-01-12T00:00:00.000Z" ) ; // success: false
To allow for dates or date strings, you can use preprocess
const dateSchema = z . preprocess ( ( arg ) => { if ( typeof arg == "string" || arg instanceof Date ) return new Date ( arg ) ; } , z . date ( ) ) ; type DateSchema = z . infer < typeof dateSchema > ; // blazon DateSchema = Date dateSchema . safeParse ( new Date ( "1/12/22" ) ) ; // success: true dateSchema . safeParse ( "2022-01-12T00:00:00.000Z" ) ; // success: truthful
Zod enums
const FishEnum = z . enum ( [ "Salmon" , "Tuna" , "Trout" ] ) ; type FishEnum = z . infer < typeof FishEnum > ; // 'Salmon' | 'Tuna' | 'Trout'
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, employ every bit const
to define your enum values as a tuple of strings. See the const assertion docs for details.
const VALUES = [ "Salmon" , "Tuna" , "Trout" ] equally const ; const FishEnum = z . enum ( VALUES ) ;
This is non allowed, since Zod isn't able to infer the exact values of each elements.
const fish = [ "Salmon" , "Tuna" , "Trout" ] ; const FishEnum = z . enum ( fish ) ;
Autocompletion
To go autocompletion with a Zod enum, use the .enum
property of your schema:
FishEnum . enum . Salmon ; // => autocompletes FishEnum . enum ; /* => { Salmon: "Salmon", Tuna: "Tuna", Trout: "Trout", } */
Yous can besides retrieve the list of options equally a tuple with the .options
property:
FishEnum . options ; // ["Salmon", "Tuna", "Trout"]);
Native enums
Zod enums are the recommended approach to defining and validating enums. But if yous need to validate against an enum from a third-political party library (or you don't want to rewrite your existing enums) you can use z.nativeEnum()
.
Numeric enums
enum Fruits { Apple , Assistant , } const FruitEnum = z . nativeEnum ( Fruits ) ; type FruitEnum = z . infer < typeof FruitEnum > ; // Fruits FruitEnum . parse ( Fruits . Apple ) ; // passes FruitEnum . parse ( Fruits . Banana ) ; // passes FruitEnum . parse ( 0 ) ; // passes FruitEnum . parse ( 1 ) ; // passes FruitEnum . parse ( three ) ; // fails
Cord enums
enum Fruits { Apple = "apple" , Banana = "assistant" , Cantaloupe , // you can mix numerical and string enums } const FruitEnum = z . nativeEnum ( Fruits ) ; type FruitEnum = z . infer < typeof FruitEnum > ; // Fruits FruitEnum . parse ( Fruits . Apple ) ; // passes FruitEnum . parse ( Fruits . Cantaloupe ) ; // passes FruitEnum . parse ( "apple" ) ; // passes FruitEnum . parse ( "banana" ) ; // passes FruitEnum . parse ( 0 ) ; // passes FruitEnum . parse ( "Cantaloupe" ) ; // fails
Const enums
The .nativeEnum()
function works for equally const
objects equally well. as const
required TypeScript 3.iv+!
const Fruits = { Apple: "apple tree" , Banana: "assistant" , Cantaloupe: 3 , } equally const ; const FruitEnum = z . nativeEnum ( Fruits ) ; type FruitEnum = z . infer < typeof FruitEnum > ; // "apple" | "banana" | three FruitEnum . parse ( "apple" ) ; // passes FruitEnum . parse ( "banana" ) ; // passes FruitEnum . parse ( iii ) ; // passes FruitEnum . parse ( "Cantaloupe" ) ; // fails
You lot can admission the underlying object with the .enum
property:
FruitEnum . enum . Apple tree ; // "apple"
Optionals
You tin can make any schema optional with z.optional()
:
const schema = z . optional ( z . string ( ) ) ; schema . parse ( undefined ) ; // => returns undefined type A = z . infer < typeof schema > ; // string | undefined
You can make an existing schema optional with the .optional()
method:
const user = z . object ( { username: z . string ( ) . optional ( ) , } ) ; type C = z . infer < typeof user > ; // { username?: cord | undefined };
.unwrap
const stringSchema = z . string ( ) ; const optionalString = stringSchema . optional ( ) ; optionalString . unwrap ( ) === stringSchema ; // true
Nullables
Similarly, you lot tin can create nullable types like so:
const nullableString = z . nullable ( z . cord ( ) ) ; nullableString . parse ( "asdf" ) ; // => "asdf" nullableString . parse ( aught ) ; // => zilch
You can make an existing schema nullable with the nullable
method:
const E = z . string ( ) . nullable ( ) ; // equivalent to D type E = z . infer < typeof E > ; // string | zero
.unwrap
const stringSchema = z . string ( ) ; const nullableString = stringSchema . nullable ( ) ; nullableString . unwrap ( ) === stringSchema ; // true
Objects
// all properties are required by default const Canis familiaris = z . object ( { name: z . string ( ) , age: z . number ( ) , } ) ; // excerpt the inferred type similar this blazon Dog = z . infer < typeof Dog > ; // equivalent to: type Canis familiaris = { proper noun: string ; historic period: number ; } ;
.shape
Use .shape
to admission the schemas for a particular fundamental.
Dog . shape . proper name ; // => cord schema Dog . shape . age ; // => number schema
.extend
You can add additional fields an object schema with the .extend
method.
const DogWithBreed = Dog . extend ( { brood: z . cord ( ) , } ) ;
Y'all can utilise .extend
to overwrite fields! Be careful with this ability!
.merge
Equivalent to A.extend(B.shape)
.
const BaseTeacher = z . object ( { students: z . array ( z . string ( ) ) } ) ; const HasID = z . object ( { id: z . cord ( ) } ) ; const Teacher = BaseTeacher . merge ( HasID ) ; blazon Teacher = z . infer < typeof Teacher > ; // => { students: cord[], id: string }
If the ii schemas share keys, the backdrop of B overrides the belongings of A. The returned schema besides inherits the "unknownKeys" policy (strip/strict/passthrough) and the catchall schema of B.
.option/.omit
Inspired by TypeScript's built-in Choice
and Omit
utility types, all Zod object schemas have .option
and .omit
methods that return a modified version. Consider this Recipe schema:
const Recipe = z . object ( { id: z . string ( ) , name: z . cord ( ) , ingredients: z . assortment ( z . string ( ) ) , } ) ;
To only proceed sure keys, utilize .option
.
const JustTheName = Recipe . option ( { proper noun: true } ) ; type JustTheName = z . infer < typeof JustTheName > ; // => { proper noun: cord }
To remove sure keys, apply .omit
.
const NoIDRecipe = Recipe . omit ( { id: true } ) ; type NoIDRecipe = z . infer < typeof NoIDRecipe > ; // => { name: string, ingredients: cord[] }
.partial
Inspired by the built-in TypeScript utility type Partial, the .partial
method makes all backdrop optional.
Starting from this object:
const user = z . object ( { e-mail: z . string ( ) username: z . string ( ) , } ) ; // { email: string; username: string }
We tin can create a fractional version:
const partialUser = user . partial ( ) ; // { email?: cord | undefined; username?: string | undefined }
You can also specify which backdrop to make optional:
const optionalEmail = user . partial ( { email: truthful , } ) ; /* { email?: string | undefined; username: string } */
.deepPartial
The .partial
method is shallow — it only applies one level deep. There is also a "deep" version:
const user = z . object ( { username: z . string ( ) , location: z . object ( { breadth: z . number ( ) , longitude: z . number ( ) , } ) , strings: z . array ( z . object ( { value: z . string ( ) } ) ) , } ) ; const deepPartialUser = user . deepPartial ( ) ; /* { username?: cord | undefined, location?: { latitude?: number | undefined; longitude?: number | undefined; } | undefined, strings?: { value?: cord}[] } */
Important limitation: deep partials only work as expected in hierarchies of objects, arrays, and tuples.
Unrecognized keys
By default Zod objects schemas strip out unrecognized keys during parsing.
const person = z . object ( { proper noun: z . string ( ) , } ) ; person . parse ( { name: "bob dylan" , extraKey: 61 , } ) ; // => { name: "bob dylan" } // extraKey has been stripped
.passthrough
Instead, if you desire to pass through unknown keys, use .passthrough()
.
person . passthrough ( ) . parse ( { name: "bob dylan" , extraKey: 61 , } ) ; // => { name: "bob dylan", extraKey: 61 }
.strict
You can disallow unknown keys with .strict()
. If there are whatever unknown keys in the input, Zod will throw an error.
const person = z . object ( { proper noun: z . string ( ) , } ) . strict ( ) ; person . parse ( { name: "bob dylan" , extraKey: 61 , } ) ; // => throws ZodError
.strip
You tin can use the .strip
method to reset an object schema to the default behavior (stripping unrecognized keys).
.catchall
You can laissez passer a "catchall" schema into an object schema. All unknown keys will be validated against it.
const person = z . object ( { name: z . string ( ) , } ) . catchall ( z . number ( ) ) ; person . parse ( { name: "bob dylan" , validExtraKey: 61 , // works fine } ) ; person . parse ( { name: "bob dylan" , validExtraKey: imitation , // fails } ) ; // => throws ZodError
Using .catchall()
obviates .passthrough()
, .strip()
, or .strict()
. All keys are now considered "known".
Arrays
const stringArray = z . array ( z . string ( ) ) ; // equivalent const stringArray = z . string ( ) . array ( ) ;
Be careful with the .array()
method. It returns a new ZodArray
case. This ways the social club in which you call methods matters. For instance:
z . cord ( ) . optional ( ) . array ( ) ; // (string | undefined)[] z . cord ( ) . assortment ( ) . optional ( ) ; // string[] | undefined
.element
Use .element
to access the schema for an element of the array.
stringArray . element ; // => cord schema
.nonempty
If you want to ensure that an array contains at least one element, use .nonempty()
.
const nonEmptyStrings = z . string ( ) . array ( ) . nonempty ( ) ; // the inferred type is now // [string, ...string[]] nonEmptyStrings . parse ( [ ] ) ; // throws: "Assortment cannot be empty" nonEmptyStrings . parse ( [ "Ariana Grande" ] ) ; // passes
Y'all tin optionally specify a custom error message:
// optional custom error bulletin const nonEmptyStrings = z . string ( ) . array ( ) . nonempty ( { message: "Can't be empty!" , } ) ;
.min/.max/.length
z . string ( ) . array ( ) . min ( five ) ; // must contain 5 or more items z . cord ( ) . assortment ( ) . max ( 5 ) ; // must contain 5 or fewer items z . string ( ) . assortment ( ) . length ( 5 ) ; // must incorporate v items exactly
Different .nonempty()
these methods do non change the inferred type.
Tuples
Different arrays, tuples have a fixed number of elements and each element can have a different type.
const athleteSchema = z . tuple ( [ z . cord ( ) , // name z . number ( ) , // bailiwick of jersey number z . object ( { pointsScored: z . number ( ) , } ) , // statistics ] ) ; blazon Athlete = z . infer < typeof athleteSchema > ; // type Athlete = [cord, number, { pointsScored: number }]
Unions
Zod includes a born z.matrimony
method for composing "OR" types.
const stringOrNumber = z . spousal relationship ( [ z . string ( ) , z . number ( ) ] ) ; stringOrNumber . parse ( "foo" ) ; // passes stringOrNumber . parse ( 14 ) ; // passes
Zod will test the input against each of the "options" in social club and return the first value that validates successfully.
For convenience, you can also employ the .or
method:
const stringOrNumber = z . string ( ) . or ( z . number ( ) ) ;
Discriminated unions
If the union consists of object schemas all identifiable past a common holding, it is possible to use the z.discriminatedUnion
method.
The advantage is in more efficient evaluation and more human being friendly errors. With the bones union method the input is tested against each of the provided "options", and in the case of invalidity, problems for all the "options" are shown in the zod error. On the other manus, the discriminated union allows for selecting just i of the "options", testing against information technology, and showing only the problems related to this "option".
const item = z . discriminatedUnion ( "blazon" , [ z . object ( { type: z . literal ( "a" ) , a: z . cord ( ) } ) , z . object ( { type: z . literal ( "b" ) , b: z . string ( ) } ) , ] ) . parse ( { type: "a" , a: "abc" } ) ;
Records
Tape schemas are used to validate types such as { [k: string]: number }
.
If you desire to validate the values of an object against some schema but don't care about the keys, apply Record
.
const NumberCache = z . record ( z . number ( ) ) ; blazon NumberCache = z . infer < typeof NumberCache > ; // => { [k: string]: number }
This is specially useful for storing or caching items by ID.
const userStore: UserStore = { } ; userStore [ "77d2586b-9e8e-4ecf-8b21-ea7e0530eadd" ] = { name: "Carlotta" , } ; // passes userStore [ "77d2586b-9e8e-4ecf-8b21-ea7e0530eadd" ] = { whatever: "Ice cream sundae" , } ; // TypeError
A note on numerical keys
You may accept expected z.record()
to accept two arguments, ane for the keys and one for the values. After all, TypeScript'due south built-in Record type does: Tape<KeyType, ValueType>
. Otherwise, how do you represent the TypeScript type Record<number, whatever>
in Zod?
As information technology turns out, TypeScript'south beliefs surrounding [k: number]
is a little unintuitive:
const testMap: { [ k: number ]: cord } = { 1: "one" , } ; for ( const key in testMap ) { console . log ( ` ${ key } : ${ typeof key } ` ) ; } // prints: `one: string`
As you tin can run across, 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 fashion of creating a record schema with numerical keys, since there's no such thing as a numerical key in runtime JavaScript.
Maps
const stringNumberMap = z . map ( z . string ( ) , z . number ( ) ) ; blazon StringNumberMap = z . infer < typeof stringNumberMap > ; // type StringNumberMap = Map<string, number>
Sets
const numberSet = z . set ( z . number ( ) ) ; type NumberSet = z . infer < typeof numberSet > ; // type NumberSet = Set<number>
.nonempty/.min/.max/.size
z . fix ( z . string ( ) ) . nonempty ( ) ; // must incorporate at least one item z . set ( z . string ( ) ) . min ( five ) ; // must contain 5 or more items z . ready ( z . cord ( ) ) . max ( v ) ; // must comprise 5 or fewer items z . set ( z . cord ( ) ) . size ( five ) ; // must contain 5 items exactly
Intersections
Intersections are useful for creating "logical AND" types. This is useful for intersecting two object types.
const Person = z . object ( { proper name: z . string ( ) , } ) ; const Employee = z . object ( { part: z . string ( ) , } ) ; const EmployedPerson = z . intersection ( Person , Employee ) ; // equivalent to: const EmployedPerson = Person . and ( Employee ) ;
Though in many cases, it is recommended to utilise A.merge(B)
to merge 2 objects. The .merge
method returns a new ZodObject
instance, whereas A.and(B)
returns a less useful ZodIntersection
example that lacks common object methods like pick
and omit
.
const a = z . matrimony ( [ z . number ( ) , z . string ( ) ] ) ; const b = z . spousal relationship ( [ z . number ( ) , z . boolean ( ) ] ) ; const c = z . intersection ( a , b ) ; type c = z . infer < typeof c > ; // => number
Recursive types
You tin can ascertain a recursive schema in Zod, but because of a limitation of TypeScript, their type can't exist statically inferred. Instead you'll need to define the blazon definition manually, and provide it to Zod every bit a "blazon hint".
interface Category { name: string ; subcategories: Category [ ] ; } // cast to z.ZodType<Category> const Category: z . ZodType < Category > = z . lazy ( ( ) => z . object ( { proper noun: z . cord ( ) , subcategories: z . assortment ( Category ) , } ) ) ; Category . parse ( { name: "People" , subcategories: [ { proper noun: "Politicians" , subcategories: [ { name: "Presidents" , subcategories: [ ] } ] , } , ] , } ) ; // passes
Unfortunately this code is a bit duplicative, since you're declaring the types twice: in one case in the interface and again in the Zod definition.
JSON type
If you want to validate whatever JSON value, you can apply the snippet beneath.
blazon Literal = boolean | nil | number | string ; type Json = Literal | { [ key: string ]: Json } | Json [ ] ; const literalSchema = z . union ( [ z . cord ( ) , z . number ( ) , z . boolean ( ) , z . nil ( ) ] ) ; const jsonSchema: z . ZodType < Json > = z . lazy ( ( ) => z . wedlock ( [ literalSchema , z . array ( jsonSchema ) , z . record ( jsonSchema ) ] ) ) ; jsonSchema . parse ( data ) ;
Thanks to ggoodman for suggesting this.
Cyclical objects
Despite supporting recursive schemas, passing cyclical data into Zod will crusade an infinite loop.
Promises
const numberPromise = z . promise ( z . number ( ) ) ;
"Parsing" works a trivial differently with promise schemas. Validation happens in two parts:
- Zod synchronously checks that the input is an example of Promise (i.e. an object with
.and so
and.catch
methods.). - Zod uses
.and then
to attach an additional validation step onto the existing Promise. You'll take to utilise.catch
on the returned Hope to handle validation failures.
numberPromise . parse ( "tuna" ) ; // ZodError: Non-Hope type: string numberPromise . parse ( Promise . resolve ( "tuna" ) ) ; // => Promise<number> const test = async ( ) => { await numberPromise . parse ( Hope . resolve ( "tuna" ) ) ; // ZodError: Non-number type: string await numberPromise . parse ( Hope . resolve ( 3.14 ) ) ; // => iii.14 } ;
Instanceof
You can use z.instanceof
to check that the input is an instance of a class. This is useful to validate inputs against classes that are exported from third-party libraries.
grade Test { name: string ; } const TestSchema = z . instanceof ( Test ) ; const blob: any = "whatever" ; TestSchema . parse ( new Test ( ) ) ; // passes TestSchema . parse ( "blob" ) ; // throws
Function schemas
Zod also lets you define "function schemas". This makes it like shooting fish in a barrel to validate the inputs and outputs of a function without intermixing your validation lawmaking and "concern logic".
Y'all can create a function schema with z.function(args, returnType)
.
const myFunction = z . function ( ) ; type myFunction = z . infer < typeof myFunction > ; // => ()=>unknown
Define inputs and output
const myFunction = z . function ( ) . args ( z . cord ( ) , z . number ( ) ) // accepts an arbitrary number of arguments . returns ( z . boolean ( ) ) ; type myFunction = z . infer < typeof myFunction > ; // => (arg0: string, arg1: number)=>boolean
Extract the input and output schemas Yous can extract the parameters and return type of a role schema.
myFunction . parameters ( ) ; // => ZodTuple<[ZodString, ZodNumber]> myFunction . returnType ( ) ; // => ZodBoolean
You can utilize the special
z.void()
selection if your office doesn't return anything. This will allow Zod properly infer the type of void-returning functions. (Void-returning functions actually return undefined.)
Function schemas accept an .implement()
method which accepts a function and returns a new function that automatically validates it's inputs and outputs.
const trimmedLength = z . function ( ) . args ( z . cord ( ) ) // accepts an arbitrary number of arguments . returns ( z . number ( ) ) . implement ( ( ten ) => { // TypeScript knows ten is a string! return x . trim ( ) . length ; } ) ; trimmedLength ( "sandwich" ) ; // => 8 trimmedLength ( " asdf " ) ; // => 4
If you only care about validating inputs, that's fine:
const myFunction = z . part ( ) . args ( z . string ( ) ) . implement ( ( arg ) => { render [ arg . length ] ; // } ) ; myFunction ; // (arg: string)=>number[]
Preprocess
Typically Zod operates under a "parse and so transform" paradigm. Zod validates the input showtime, then passes information technology through a chain of transformation functions. (For more information virtually transforms, read the .transform docs.)
Just sometimes you want to apply some transform to the input earlier parsing happens. A common utilize case: type coercion. Zod enables this with the z.preprocess()
.
const castToString = z . preprocess ( ( val ) => String ( val ) , z . cord ( ) ) ;
This returns a ZodEffects
instance. ZodEffects
is a wrapper class that contains all logic pertaining to preprocessing, refinements, and transforms.
ZodType: methods and properties
All Zod schemas contain certain methods.
.parse
.parse(data:unknown): T
Given any Zod schema, you tin call its .parse
method to check data
is valid. If information technology is, a value is returned with full blazon information! Otherwise, an fault is thrown.
IMPORTANT: In Zod 2 and Zod 1.11+, the value returned past
.parse
is a deep clone of the variable you passed in. This was also the case in zod@i.4 and earlier.
const stringSchema = z . string ( ) ; stringSchema . parse ( "fish" ) ; // => returns "fish" stringSchema . parse ( 12 ) ; // throws Mistake('Not-cord type: number');
.parseAsync
.parseAsync(data:unknown): Promise<T>
If y'all use asynchronous refinements or transforms (more on those later), you'll need to utilize .parseAsync
const stringSchema = z . cord ( ) . refine ( async ( val ) => val . length > 20 ) ; const value = wait stringSchema . parseAsync ( "hello" ) ; // => hello
.safeParse
.safeParse(data:unknown): { success: true; data: T; } | { success: faux; error: ZodError; }
If you don't want Zod to throw errors when validation fails, use .safeParse
. This method returns an object containing either the successfully parsed data or a ZodError instance containing detailed information about the validation problems.
stringSchema . safeParse ( 12 ) ; // => { success: false; mistake: ZodError } stringSchema . safeParse ( "billie" ) ; // => { success: true; data: 'billie' }
The result is a discriminated union then yous can handle errors very conveniently:
const result = stringSchema . safeParse ( "billie" ) ; if ( ! issue . success ) { // handle fault then render issue . error ; } else { // do something upshot . data ; }
.safeParseAsync
Alias:
.spa
An asynchronous version of safeParse
.
expect stringSchema . safeParseAsync ( "billie" ) ;
For convenience, this has been aliased to .spa
:
await stringSchema . spa ( "billie" ) ;
.refine
.refine(validator: (data:T)=>any, params?: RefineParams)
Zod lets y'all provide custom validation logic via refinements. (For advanced features like creating multiple problems and customizing mistake codes, see .superRefine
.)
Zod was designed to mirror TypeScript every bit closely as possible. But there are many and so-called "refinement types" you may wish to check for that can't be represented in TypeScript's type system. For case: checking that a number is an integer or that a string is a valid email accost.
For instance, you lot tin can define a custom validation cheque on any Zod schema with .refine
:
const myString = z . string ( ) . refine ( ( val ) => val . length <= 255 , { message: "String tin can't be more than 255 characters" , } ) ;
⚠️ Refinement functions should not throw. Instead they should return a falsy value to signal failure.
Arguments
As you can see, .refine
takes two arguments.
- The first is the validation function. This office takes i input (of type
T
— the inferred blazon of the schema) and returnsany
. Whatsoever truthy value volition pass validation. (Prior to zod@1.6.2 the validation role had to return a boolean.) - The second argument accepts some options. You tin can apply this to customize certain fault-handling behavior:
type RefineParams = { // override error bulletin message?: cord ; // appended to error path path?: ( string | number ) [ ] ; // params object you tin can use to customize message // in mistake map params?: object ; } ;
For advanced cases, the 2nd argument tin can likewise exist a function that returns RefineParams
/
z . cord ( ) . refine ( ( val ) => val . length > ten , ( val ) => ( { message: ` ${ val } is not more than x characters` } ) ) ;
Customize error path
const passwordForm = z . object ( { password: z . cord ( ) , confirm: z . string ( ) , } ) . refine ( ( data ) => information . password === data . ostend , { message: "Passwords don't match" , path: [ "confirm" ] , // path of error } ) . parse ( { password: "asdf" , confirm: "qwer" } ) ;
Considering you provided a path
parameter, the resulting mistake will be:
ZodError { problems: [ { "lawmaking": "custom" , "path": [ "confirm" ] , "message": "Passwords don't match" } ] }
Asynchronous refinements
Refinements can besides exist async:
const userId = z . cord ( ) . refine ( async ( id ) => { // verify that ID exists in database render true ; } ) ;
⚠️ If you apply async refinements, you must employ the.parseAsync
method to parse data! Otherwise Zod volition throw an fault.
Relationship to transforms
Transforms and refinements tin can be interleaved:
z . cord ( ) . transform ( ( val ) => val . length ) . refine ( ( val ) => val > 25 ) ;
.superRefine
The .refine
method is really syntactic sugar atop a more versatile (and verbose) method called superRefine
. Here'southward an example:
const Strings = z . array ( z . string ( ) ) . superRefine ( ( val , ctx ) => { if ( val . length > 3 ) { ctx . addIssue ( { lawmaking: z . ZodIssueCode . too_big , maximum: iii , type: "array" , inclusive: truthful , message: "Besides many items 😡" , } ) ; } if ( val . length !== new Set up ( val ) . size ) { ctx . addIssue ( { code: z . ZodIssueCode . custom , bulletin: `No duplicated allowed.` , } ) ; } } ) ;
You tin add as many problems as you like. If ctx.addIssue
is NOT called during the execution of the function, validation passes.
Normally refinements e'er create issues with a ZodIssueCode.custom
error lawmaking, but with superRefine
you can create whatsoever issue of any lawmaking. Each issue code is described in detail in the Error Handling guide: ERROR_HANDLING.md.
Arrest early
By default, parsing will continue even subsequently a refinement check fails. For example, if you chain together multiple refinements, they volition all be executed. However, it may exist desirable to abort early to prevent after refinements from being executed. To achieve this, pass the fatal
flag to ctx.addIssue
:
const Strings = z . number ( ) . superRefine ( ( val , ctx ) => { if ( val < x ) { ctx . addIssue ( { code: z . ZodIssueCode . custom , message: "foo" , fatal: true , } ) ; } } ) . superRefine ( ( val , ctx ) => { if ( val !== " " ) { ctx . addIssue ( { code: z . ZodIssueCode . custom , message: "bar" , } ) ; } } ) ;
.transform
To transform data after parsing, utilize the transform
method.
const stringToNumber = z . cord ( ) . transform ( ( val ) => myString . length ) ; stringToNumber . parse ( "cord" ) ; // => half dozen
⚠️ Transform functions must not throw. Brand sure to use refinements before the transform to make sure the input can be parsed past the transform.
Chaining social club
Notation that stringToNumber
to a higher place is an instance of the ZodEffects
subclass. Information technology is Non an instance of ZodString
. If you lot want to use the built-in methods of ZodString
(e.1000. .e-mail()
) you must utilize those methods before any transforms.
const emailToDomain = z . string ( ) . e-mail ( ) . transform ( ( val ) => val . split ( "@" ) [ one ] ) ; emailToDomain . parse ( "colinhacks@example.com" ) ; // => example.com
Relationship to refinements
Transforms and refinements tin can be interleaved:
z . string ( ) . transform ( ( val ) => val . length ) . refine ( ( val ) => val > 25 ) ;
Async transforms
Transforms can also exist async.
const IdToUser = z . cord ( ) . uuid ( ) . transform ( async ( id ) => { return await getUserById ( id ) ; } ) ;
⚠️ If your schema contains asynchronous transforms, you must use .parseAsync() or .safeParseAsync() to parse information. Otherwise Zod will throw an error.
.default
You can use transforms to implement the concept of "default values" in Zod.
const stringWithDefault = z . string ( ) . default ( "tuna" ) ; stringWithDefault . parse ( undefined ) ; // => "tuna"
Optionally, you tin can pass a function into .default
that will exist re-executed whenever a default value needs to be generated:
const numberWithRandomDefault = z . number ( ) . default ( Math . random ) ; numberWithRandomDefault . parse ( undefined ) ; // => 0.4413456736055323 numberWithRandomDefault . parse ( undefined ) ; // => 0.1871840107401901 numberWithRandomDefault . parse ( undefined ) ; // => 0.7223408162401552
.optional
A convenience method that returns an optional version of a schema.
const optionalString = z . cord ( ) . optional ( ) ; // string | undefined // equivalent to z . optional ( z . string ( ) ) ;
.nullable
A convenience method that returns an nullable version of a schema.
const nullableString = z . string ( ) . nullable ( ) ; // string | nada // equivalent to z . nullable ( z . cord ( ) ) ;
.nullish
A convenience method that returns a "nullish" version of a schema. Nullish schemas will accept both undefined
and nada
. Read more most the concept of "nullish" here.
const nullishString = z . string ( ) . nullish ( ) ; // string | nada | undefined // equivalent to z . string ( ) . optional ( ) . nullable ( ) ;
.assortment
A convenience method that returns an array schema for the given blazon:
const nullableString = z . string ( ) . array ( ) ; // cord[] // equivalent to z . array ( z . string ( ) ) ;
.hope
A convenience method for promise types:
const stringPromise = z . string ( ) . promise ( ) ; // Promise<cord> // equivalent to z . promise ( z . string ( ) ) ;
.or
A convenience method for union types.
z . cord ( ) . or ( z . number ( ) ) ; // string | number // equivalent to z . matrimony ( [ z . string ( ) , z . number ( ) ] ) ;
.and
A convenience method for creating intersection types.
z . object ( { proper name: z . string ( ) } ) . and ( z . object ( { age: z . number ( ) } ) ) ; // { name: string } & { historic period: number } // equivalent to z . intersection ( z . object ( { proper noun: z . string ( ) } ) , z . object ( { age: z . number ( ) } ) ) ;
Blazon inference
You tin excerpt the TypeScript type of whatsoever schema with z.infer<typeof mySchema>
.
const A = z . string ( ) ; blazon A = z . infer < typeof A > ; // string const u: A = 12 ; // TypeError const u: A = "asdf" ; // compiles
What well-nigh transforms?
In reality each Zod schema internally tracks two types: an input and an output. For most schemas (east.one thousand. z.string()
) these two are the same. Simply in one case you add transforms into the mix, these two values can diverge. For instance z.string().transform(val => val.length)
has an input of string
and an output of number
.
You tin separately extract the input and output types like and then:
const stringToNumber = z . string ( ) . transform ( ( val ) => val . length ) ; // ⚠️ Important: z.infer returns the OUTPUT type! blazon input = z . input < typeof stringToNumber > ; // string type output = z . output < typeof stringToNumber > ; // number // equivalent to z.output! type inferred = z . infer < typeof stringToNumber > ; // number
Errors
Zod provides a subclass of Error called ZodError
. ZodErrors incorporate an bug
assortment containing detailed information about the validation problems.
const data = z . object ( { name: z . cord ( ) , } ) . safeParse ( { proper name: 12 } ) ; if ( ! data . success ) { data . error . problems ; /* [ { "code": "invalid_type", "expected": "cord", "received": "number", "path": [ "name" ], "message": "Expected string, received number" } ] */ }
Error formatting
You can use the .format()
method to convert this error into a nested object.
data . error . format ( ) ; /* { name: { _errors: [ 'Expected string, received number' ] } } */
For detailed information about the possible error codes and how to customize mistake messages, check out the dedicated error handling guide: ERROR_HANDLING.md
Comparing
In that location are a scattering of other widely-used validation libraries, but all of them have certain blueprint limitations that make for a non-platonic developer experience.
Joi
https://github.com/hapijs/joi
Doesn't support static type inference
Yup
https://github.com/jquense/yup
Yup is a full-featured library that was implemented starting time in vanilla JS, and after rewritten in TypeScript.
Differences
- Supports casting and transforms
- All object fields are optional past default
- Missing object methods: (partial, deepPartial)
- Missing promise schemas
- Missing function schemas
- Missing union & intersection schemas
io-ts
https://github.com/gcanti/io-ts
io-ts is an splendid library by gcanti. The API of io-ts heavily inspired the pattern of Zod.
In our experience, io-ts prioritizes functional programming purity over programmer experience in many cases. This is a valid and beauteous design goal, just it makes io-ts particularly hard to integrate into an existing codebase with a more procedural or object-oriented bias. For case, consider how to define an object with optional backdrop in io-ts:
import * as t from "io-ts" ; const A = t . type ( { foo: t . string , } ) ; const B = t . fractional ( { bar: t . number , } ) ; const C = t . intersection ( [ A , B ] ) ; type C = t . TypeOf < typeof C > ; // returns { foo: string; bar?: number | undefined }
You must ascertain the required and optional props in separate object validators, pass the optionals through t.partial
(which marks all properties every bit optional), then combine them with t.intersection
.
Consider the equivalent in Zod:
const C = z . object ( { foo: z . string ( ) , bar: z . number ( ) . optional ( ) , } ) ; type C = z . infer < typeof C > ; // returns { foo: string; bar?: number | undefined }
This more declarative API makes schema definitions vastly more concise.
io-ts
also requires the utilize of gcanti'south functional programming library fp-ts
to parse results and handle errors. This is some other fantastic resources 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
classification to use the library.
- Supports codecs with serialization & deserialization transforms
- Supports branded types
- Supports advanced functional programming, higher-kinded types,
fp-ts
compatibility - Missing object methods: (option, omit, partial, deepPartial, merge, extend)
- Missing nonempty arrays with proper typing (
[T, ...T[]]
) - Missing hope schemas
- Missing function schemas
Runtypes
https://github.com/pelotom/runtypes
Good blazon inference support, just express options for object blazon masking (no .pick
, .omit
, .extend
, etc.). No support for Record
due south (their Tape
is equivalent to Zod'south object
). They Do support branded and readonly types, which Zod does not.
- Supports "pattern matching": computed properties that distribute over unions
- Supports readonly types
- Missing object methods: (deepPartial, merge)
- Missing nonempty arrays with proper typing (
[T, ...T[]]
) - Missing promise schemas
- Missing error customization
Ow
https://github.com/sindresorhus/ow
Ow is focused on function input validation. It's a library that makes it easy to express complicated assert statements, simply information technology 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 blazon system, whereas ow lets you validate several highly-specific types out of the box (e.grand. int32Array
, see full list in their README).
If you want to validate function inputs, utilise office schemas in Zod! It's a much simpler arroyo that lets you reuse a role type proclamation without repeating yourself (namely, copy-pasting a bunch of ow assertions at the beginning of every function). As well Zod lets you validate your return types equally well, so you tin can be certain there won't be whatsoever unexpected data passed downstream.
Changelog
View the changelog at CHANGELOG.doctor
Source: https://www.npmjs.com/package/zod
Post a Comment for "Cannot Read Property 'match' of Undefined Npm"