Zod

  • To validate the schema and auto-generate the type in order to make sure the type must be correct

import { z } from "zod";

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

// validate: if correct return object, else throw error
const user = User.parse({ username: "Ludwig" });

// extract the inferred type
type User = z.infer<typeof User>;
// { username: string }


// refinement
const schemaWithRefine = z
  .object({
    password: z.string().min(8),
    confirmPassword: z.string().min(8),
  })
  .refine((data) => data.password === data.confirmPassword, {
    message: "Passwords do not match",
    path: ["confirmPassword"], 
    // This will attach the error to the confirmPassword field
  });
  
// combining schemas

// method 1
// support object only
// after merge can keep the object behaviour, e.g: pick,...
const schema1 = z
  .object({
    name: z.string(),
  })

const schema2 = z.object({
  email: z.string().email(),
});
const mergedWithShape = schema1.merge(schema2).;

// method 2 (intersection)
// more flexibility, support refine, transform and non-object schema
const schema1 = z
  .object({
    name: z.string(),
  })

const schema2 = z
  .object({
    password: z.string().min(8),
    confirmPassword: z.string().min(8),
  })
  .refine((data) => data.password === data.confirmPassword, {
    message: "Passwords do not match",
    path: ["confirmPassword"], 
    // This will attach the error to the confirmPassword field
  });
const mergedWithShape = z.intersection(schema1, schema2)

Last updated

Was this helpful?