TypeScript to Zod Schema Generator

5.1.0 · active · verified Sun Apr 19

ts-to-zod is a powerful utility designed to automatically generate Zod schemas directly from existing TypeScript types and interfaces. Currently stable at version 5.1.0, the library maintains a relatively active release cadence, frequently incorporating new features and bug fixes, with major version bumps often synchronized with Zod's own major releases. Its core differentiation lies in its direct interaction with the TypeScript Abstract Syntax Tree (AST), ensuring high fidelity in schema generation. It also offers advanced features such as enhancing schemas via JSDoc tags (e.g., `@minimum`, `@maxLength`) and includes an internal validation step to verify that generated schemas are fully compatible with their original TypeScript types, minimizing discrepancies. This tool significantly streamlines the process of adding robust runtime validation to TypeScript projects.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to install ts-to-zod, generate Zod schemas from a TypeScript type definition file using the CLI, and then import and use the generated schemas for runtime validation.

// 1. Install ts-to-zod
// pnpm add --dev ts-to-zod
// or yarn add --dev ts-to-zod
// or npm install --save-dev ts-to-zod

// 2. Create a TypeScript type file (e.g., src/types.ts)
// export interface User {
//   id: string;
//   name: string;
//   email: string | null;
//   age?: number;
//   roles: 'admin' | 'editor' | 'viewer'[];
//   createdAt: Date;
// }

// 3. Generate Zod schemas using the CLI
// pnpm ts-to-zod src/types.ts src/schemas.ts

// 4. In another file (e.g., src/app.ts), import and use the generated schemas
import { UserSchema } from './schemas'; // Assuming User becomes UserSchema

// Example data conforming to the User type
const userData = {
  id: '123',
  name: 'John Doe',
  email: 'john@example.com',
  age: 30,
  roles: ['admin', 'viewer'],
  createdAt: new Date().toISOString(), // Zod's .datetime() expects ISO string by default
};

// Validate the data
try {
  const parsedUser = UserSchema.parse(userData);
  console.log('User data is valid:', parsedUser);
  // parsedUser now has the correct TypeScript type inferred from Zod: z.infer<typeof UserSchema>
} catch (error) {
  console.error('Validation error:', error);
}

// Example of invalid data
const invalidUserData = {
  id: 456, // Invalid type
  name: 'Jane Doe',
  email: null,
  roles: 'editor', // Invalid type, should be array
  createdAt: 'not-a-date', // Invalid date format
};

try {
  UserSchema.parse(invalidUserData);
} catch (error) {
  console.error('\nInvalid user data failed validation as expected:', error.errors);
}

view raw JSON →