最終更新:2023-07-19 (水) 11:09:53 (305d)  

zod
Top / zod

  • import { z } from "zod";

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
    
    // "safe" parsing (doesn't throw error if validation fails)
    mySchema.safeParse("tuna"); // => { success: true; data: "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" });
    
    // extract the inferred type
    type User = z.infer<typeof User>;
    // { username: string }

Primitives

  • import { z } from "zod";
    
    // primitive values
    z.string();
    z.number();
    z.bigint();
    z.boolean();
    z.date();
    z.symbol();
    
    // empty types
    z.undefined();
    z.null();
    z.void(); // accepts undefined
    
    // catch-all types
    // allows any value
    z.any();
    z.unknown();
    
    // never type
    // allows no values
    z.never();