20 stable releases
1.1.19 | Aug 4, 2025 |
---|---|
1.1.18 | Aug 1, 2025 |
1.1.4 | Jul 30, 2025 |
1.0.0 | Jul 29, 2025 |
0.1.0 | Jul 25, 2025 |
#1441 in Web programming
Used in zod_gen_derive
11KB
179 lines
zod_gen
Core library for generating Zod schemas from Rust types.
Features
ZodSchema
trait for defining schemas- Helper functions for building Zod expressions
ZodGenerator
for batch file generation- Built-in implementations for primitive types
Usage
use zod_gen::{ZodSchema, zod_object, zod_string, zod_number};
struct User {
id: u64,
name: String,
}
impl ZodSchema for User {
fn type_name() -> String { "User".to_string() }
fn zod_schema() -> String {
zod_object(&[
("id", zod_number()),
("name", zod_string()),
])
}
}
For more examples and documentation, see the main repository.
lib.rs
:
Zod Schema Generation for Rust Types
Generate Zod schemas and TypeScript types from Rust types with full serde rename support.
Quick Start with Derive Macro (Recommended)
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"] }
Dependencies
~0.6–1.5MB
~31K SLoC