Crate zod_gen

Crate zod_gen 

Source
Expand description

§Zod Schema Generation for Rust Types

Generate Zod schemas and TypeScript types from Rust types with full serde rename support.

use zod_gen::{ZodSchema, ZodGenerator};
use zod_gen_derive::ZodSchema;
use serde::{Serialize, Deserialize};

#[derive(ZodSchema, Serialize, Deserialize)]
struct User {
    id: u32,
    name: String,
    email: Option<String>,
}

#[derive(ZodSchema, Serialize, Deserialize)]
enum Status {
    #[serde(rename = "active")]
    Active,
    #[serde(rename = "inactive")]
    Inactive,
}

let mut generator = ZodGenerator::new();
generator.add_schema::<User>("User");
generator.add_schema::<Status>("Status");

let typescript = generator.generate();
// typescript contains the generated Zod schemas

This generates:

// Automatically generated by zod_gen
import * as z from 'zod';

export const UserSchema = z.object({
  id: z.number(),
  name: z.string(),
  email: z.string().nullable()
});
export type User = z.infer<typeof UserSchema>;

export const StatusSchema = z.union([z.literal("active"), z.literal("inactive")]);
export type Status = z.infer<typeof StatusSchema>;

§Manual Implementation

For custom schema generation, implement the ZodSchema trait manually:

use zod_gen::{ZodSchema, zod_object, zod_string};

struct CustomType {
    field: String,
}

impl ZodSchema for CustomType {
    fn zod_schema() -> String {
        zod_object(&[("field", zod_string())])
    }
}

§Features

  • Derive Macro: Automatic schema generation with #[derive(ZodSchema)]
  • Serde Rename Support: Full support for #[serde(rename = "...")] attributes
  • Type Safety: Generated TypeScript types match your Rust types exactly
  • Generic Types: Built-in support for Option<T>, Vec<T>, HashMap<String, T>
  • Batch Generation: Generate multiple schemas in a single TypeScript file

§Installation

Add both crates to your Cargo.toml:

[dependencies]
zod_gen = "1.1.7"
zod_gen_derive = "1.1.7"
serde = { version = "1.0", features = ["derive"] }

Structs§

ZodGenerator
Generator that collects schemas and writes TypeScript files

Traits§

ZodSchema
Trait for Rust types that can produce a Zod schema

Functions§

zod_array
zod_bigint
zod_boolean
zod_enum
zod_nullable
zod_number
zod_object
zod_record
zod_string
Helper functions for building Zod schema strings