Skip to Content

Basic - Zod

TypeScript-first schema validation with static type inference

https://zod.dev/Β 

yarn add zod

Basic Types

The basic usage is as follow

import { z } from "zod"; const User = z.object({ id: z.number(), username: z.string().min(1), desc: z.string().max(255), email: z.string().email(), banned: z.boolean(), birthday: z.date(), // remarks: string | null remarks: z.string().nullable(), // username?: string | undefined otherRemarks: z.string().optional() }); User.parse({ id: 1, username: "tom", desc: "Hi, I am Tom.", email: "tom@gmail.com", banned: false, birthday: new Date(), remarks: null }); type UserScheme = z.infer<typeof User>;

Extends

Extend on other classes

import { z } from "zod"; const StudentUser = User.extend({ class: z.string(), });

Pick and omit

  • Pick: Select certain extend field
  • Omit: Remove certain keys, keep remaining stuff
import { z } from "zod"; // Keep this type only const JustTheEmail = User.pick({ email: true }); // { email: string } // Remove these types const Readableuser = User.omit({ id: true, banned: true, remarks: true, otherRemarks: true }); // { // username: string // desc: string // email: string // }
Last updated on