Skip to content

ZodTs Derive

The ZodTs derive macro generates TypeScript Zod schema code from Rust types, enabling shared validation between your Rust backend and TypeScript frontend.

Add the dependency:

[dependencies]
zod-rs = { version = "0.4", features = ["ts"] }
# Or use the standalone crate
zod-rs-ts = "0.4"
use zod_rs_ts::ZodTs;
#[derive(ZodTs)]
struct User {
#[zod(min_length(2), max_length(50))]
username: String,
#[zod(email)]
email: String,
#[zod(min(18.0), max(120.0), int)]
age: u32,
bio: Option<String>,
}
fn main() {
let ts_code = User::zod_ts();
println!("{}", ts_code);
// Write to file
std::fs::write("schemas/user.ts", ts_code).unwrap();
}

The above generates:

import { z } from 'zod';
export const UserSchema = z.object({
username: z.string().min(2).max(50),
email: z.string().email(),
age: z.number().int().min(18).max(120),
bio: z.string().optional()
});
export type User = z.infer<typeof UserSchema>;
Rust TypeTypeScript Zod
Stringz.string()
f32, f64z.number()
i8..i64, u8..u64z.number().int()
boolz.boolean()
Vec<T>z.array(T)
Option<T>T.optional()

The same #[zod(...)] attributes used with ZodSchema are translated to TypeScript Zod methods. See the attributes reference for the full list.