Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

TypeScript-first schema validation with static type inference

License

NotificationsYou must be signed in to change notification settings

colinhacks/zod

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Zod logo

Zod

TypeScript-first schema validation with static type inference
by@colinhacks


Zod CI statusLicensenpmdiscord serverstars

Docs  •  Discord  •  𝕏  •  Bluesky


Featured sponsor: Jazz

jazz logo

Learn more aboutfeatured sponsorships






What is Zod?

Zod is a TypeScript-first validation library. Define a schema and parse some data with it. You'll get back a strongly typed, validated result.

import*aszfrom"zod";constUser=z.object({name:z.string(),});// some untrusted data...constinput={/* stuff */};// the parsed result is validated and type safe!constdata=User.parse(input);// so you can use it with confidence :)console.log(data.name);

Features

  • Zero external dependencies
  • Works in Node.js and all modern browsers
  • Tiny:2kb core bundle (gzipped)
  • Immutable API: methods return a new instance
  • Concise interface
  • Works with TypeScript and plain JS
  • Built-in JSON Schema conversion
  • Extensive ecosystem

Installation

npm install zod

Basic usage

Before you can do anything else, you need to define a schema. For the purposes of this guide, we'll use a simple object schema.

import*aszfrom"zod";constPlayer=z.object({username:z.string(),xp:z.number(),});

Parsing data

Given any Zod schema, use.parse to validate an input. If it's valid, Zod returns a strongly-typeddeep clone of the input.

Player.parse({username:"billie",xp:100});// => returns { username: "billie", xp: 100 }

Note — If your schema uses certain asynchronous APIs likeasyncrefinements ortransforms, you'll need to use the.parseAsync() method instead.

constschema=z.string().refine(async(val)=>val.length<=8);awaitschema.parseAsync("hello");// => "hello"

Handling errors

When validation fails, the.parse() method will throw aZodError instance with granular information about the validation issues.

try{Player.parse({username:42,xp:"100"});}catch(err){if(errinstanceofz.ZodError){err.issues;/* [      {        expected: 'string',        code: 'invalid_type',        path: [ 'username' ],        message: 'Invalid input: expected string'      },      {        expected: 'number',        code: 'invalid_type',        path: [ 'xp' ],        message: 'Invalid input: expected number'      }    ] */}}

To avoid atry/catch block, you can use the.safeParse() method to get back a plain result object containing either the successfully parsed data or aZodError. The result type is adiscriminated union, so you can handle both cases conveniently.

constresult=Player.safeParse({username:42,xp:"100"});if(!result.success){result.error;// ZodError instance}else{result.data;// { username: string; xp: number }}

Note — If your schema uses certain asynchronous APIs likeasyncrefinements ortransforms, you'll need to use the.safeParseAsync() method instead.

constschema=z.string().refine(async(val)=>val.length<=8);awaitschema.safeParseAsync("hello");// => { success: true; data: "hello" }

Inferring types

Zod infers a static type from your schema definitions. You can extract this type with thez.infer<> utility and use it however you like.

constPlayer=z.object({username:z.string(),xp:z.number(),});// extract the inferred typetypePlayer=z.infer<typeofPlayer>;// use it in your codeconstplayer:Player={username:"billie",xp:100};

In some cases, the input & output types of a schema can diverge. For instance, the.transform() API can convert the input from one type to another. In these cases, you can extract the input and output types independently:

constmySchema=z.string().transform((val)=>val.length);typeMySchemaIn=z.input<typeofmySchema>;// => stringtypeMySchemaOut=z.output<typeofmySchema>;// equivalent to z.infer<typeof mySchema>// number

About

TypeScript-first schema validation with static type inference

Topics

Resources

License

Code of conduct

Stars

Watchers

Forks

Sponsor this project

 

Packages

No packages published

Contributors441

Languages


[8]ページ先頭

©2009-2025 Movatter.jp