{"id":12186,"library":"ts-to-zod","title":"TypeScript to Zod Schema Generator","description":"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.","status":"active","version":"5.1.0","language":"javascript","source_language":"en","source_url":"https://github.com/fabien0102/ts-to-zod","tags":["javascript","zod","typescript","generator","oclif"],"install":[{"cmd":"npm install ts-to-zod","lang":"bash","label":"npm"},{"cmd":"yarn add ts-to-zod","lang":"bash","label":"yarn"},{"cmd":"pnpm add ts-to-zod","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Generated schemas rely on Zod; ts-to-zod v4+ requires zod v4+","package":"zod","optional":false}],"imports":[{"note":"The primary function for programmatically generating a single Zod schema string from a TypeScript type. Supports both ESM and CJS.","wrong":"const { generateZodSchema } = require('ts-to-zod');","symbol":"generateZodSchema","correct":"import { generateZodSchema } from 'ts-to-zod';"},{"note":"Used for programmatic generation of a Zod schema file. It's a named export, not a default export.","wrong":"import generateZodSchemaFile from 'ts-to-zod';","symbol":"generateZodSchemaFile","correct":"import { generateZodSchemaFile } from 'ts-to-zod';"},{"note":"The programmatic entry point for invoking the ts-to-zod CLI from within a Node.js application. Accepts an array of arguments, similar to process.argv.","wrong":"tsToZod.run(['src/input.ts', 'src/output.ts']);","symbol":"run","correct":"import { run } from 'ts-to-zod';"}],"quickstart":{"code":"// 1. Install ts-to-zod\n// pnpm add --dev ts-to-zod\n// or yarn add --dev ts-to-zod\n// or npm install --save-dev ts-to-zod\n\n// 2. Create a TypeScript type file (e.g., src/types.ts)\n// export interface User {\n//   id: string;\n//   name: string;\n//   email: string | null;\n//   age?: number;\n//   roles: 'admin' | 'editor' | 'viewer'[];\n//   createdAt: Date;\n// }\n\n// 3. Generate Zod schemas using the CLI\n// pnpm ts-to-zod src/types.ts src/schemas.ts\n\n// 4. In another file (e.g., src/app.ts), import and use the generated schemas\nimport { UserSchema } from './schemas'; // Assuming User becomes UserSchema\n\n// Example data conforming to the User type\nconst userData = {\n  id: '123',\n  name: 'John Doe',\n  email: 'john@example.com',\n  age: 30,\n  roles: ['admin', 'viewer'],\n  createdAt: new Date().toISOString(), // Zod's .datetime() expects ISO string by default\n};\n\n// Validate the data\ntry {\n  const parsedUser = UserSchema.parse(userData);\n  console.log('User data is valid:', parsedUser);\n  // parsedUser now has the correct TypeScript type inferred from Zod: z.infer<typeof UserSchema>\n} catch (error) {\n  console.error('Validation error:', error);\n}\n\n// Example of invalid data\nconst invalidUserData = {\n  id: 456, // Invalid type\n  name: 'Jane Doe',\n  email: null,\n  roles: 'editor', // Invalid type, should be array\n  createdAt: 'not-a-date', // Invalid date format\n};\n\ntry {\n  UserSchema.parse(invalidUserData);\n} catch (error) {\n  console.error('\\nInvalid user data failed validation as expected:', error.errors);\n}\n","lang":"typescript","description":"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."},"warnings":[{"fix":"Ensure your project is configured for ESM where ts-to-zod is imported, or verify your CJS setup correctly resolves module exports. Update Node.js to a supported version for optimal compatibility.","message":"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.","severity":"breaking","affected_versions":">=5.0.0"},{"fix":"Update your project's Zod dependency to '^4' (e.g., `npm install zod@^4`) and regenerate all schemas. For Zod v3 support, use ts-to-zod v3.x series.","message":"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.","severity":"breaking","affected_versions":">=4.0.0"},{"fix":"Integrate a code formatter like Prettier or BiomeJS into your build pipeline. The recommended approach is to use `pretty-quick` or a similar tool in your post-generation scripts.","message":"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.","severity":"gotcha","affected_versions":">=5.0.0"},{"fix":"Ensure all types you wish to be validated by ts-to-zod are exported in your TypeScript files. For private types, rely on your TypeScript compiler for type safety.","message":"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.","severity":"gotcha","affected_versions":">=3.x"},{"fix":"Avoid using `--skipValidation` unless absolutely necessary for debugging or specific edge cases. Address any validation errors reported by the tool to maintain schema integrity.","message":"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.","severity":"gotcha","affected_versions":">=3.x"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"For 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.","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'.","error":"Error [ERR_REQUIRE_ESM]: require() of ES Module ...ts-to-zod/lib/index.mjs not supported."},{"fix":"First, 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.","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.","error":"ZodError: Expected string, received number"},{"fix":"Update 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.","cause":"Mismatch between the Zod version ts-to-zod was configured for (v4+) and the Zod version installed in the consuming project (v3).","error":"Type 'ZodObject<...>' is not assignable to type 'ZodType<...>' from 'zod' version 3 when ts-to-zod generates schemas for Zod v4."}],"ecosystem":"npm"}