TypeScript to Zod Schema Generator
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
-
Error [ERR_REQUIRE_ESM]: require() of ES Module ...ts-to-zod/lib/index.mjs not supported.
cause Attempting to import ts-to-zod in a CommonJS context without proper configuration, especially in Node.js environments that strictly enforce ESM module resolution for packages declaring 'type: module' or specific 'exports'.fixFor Node.js projects, ensure your importing file is an ES Module (e.g., .mjs extension or 'type: module' in package.json) or adjust your build system to handle ESM. Alternatively, if your project needs to remain CommonJS, verify your Node.js version and module resolution settings are compatible with ts-to-zod's dual CJS/ESM exports. -
ZodError: Expected string, received number
cause The generated Zod schema is not accurately reflecting the TypeScript type, or the data being validated does not conform to the expected type. This could be due to an issue with ts-to-zod's generation logic or an incorrect Zod version dependency.fixFirst, ensure you are using ts-to-zod v4+ with Zod v4+. If the issue persists, check your original TypeScript type definition for correctness and verify if any JSDoc tags are causing unexpected schema generation. If possible, remove `--skipValidation` to let ts-to-zod's internal validation catch discrepancies during generation. If the problem seems to be a bug in ts-to-zod, report it on GitHub. -
Type 'ZodObject<...>' is not assignable to type 'ZodType<...>' from 'zod' version 3 when ts-to-zod generates schemas for Zod v4.
cause Mismatch between the Zod version ts-to-zod was configured for (v4+) and the Zod version installed in the consuming project (v3).fixUpdate your project's Zod dependency to version 4 or higher (e.g., `npm install zod@^4`). If you must use Zod v3, use ts-to-zod v3.x series.
Warnings
- breaking Major version 5 introduced breaking changes by refreshing dependencies and explicitly supporting ESM. While the package maintains CJS exports, users in mixed environments or those with older Node.js setups might encounter module resolution issues, primarily related to the internal restructuring for ESM support.
- breaking Version 4 introduced support for Zod v4. Projects using ts-to-zod v4+ must upgrade their Zod dependency to v4 or higher. Generated schemas will be incompatible with Zod v3.
- gotcha As of version 5, ts-to-zod no longer embeds Prettier (or any other formatter) in its generation process. Generated schema files will not be automatically formatted.
- gotcha The internal validation mechanism, which compares generated Zod schemas against original TypeScript types, only applies to *exported* types and interfaces. Non-exported types will not be validated.
- gotcha Skipping internal schema validation using the `--skipValidation` flag is possible but strongly discouraged. This bypasses a crucial check that ensures compatibility between your TypeScript types and the generated Zod schemas, potentially leading to runtime validation errors.
Install
-
npm install ts-to-zod -
yarn add ts-to-zod -
pnpm add ts-to-zod
Imports
- generateZodSchema
const { generateZodSchema } = require('ts-to-zod');import { generateZodSchema } from 'ts-to-zod'; - generateZodSchemaFile
import generateZodSchemaFile from 'ts-to-zod';
import { generateZodSchemaFile } from 'ts-to-zod'; - run
tsToZod.run(['src/input.ts', 'src/output.ts']);
import { run } from 'ts-to-zod';
Quickstart
// 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);
}