Zod to TypeScript Type Generator

2.0.0 · active · verified Sun Apr 19

zod-to-ts generates TypeScript type definitions directly from Zod schemas, converting Zod's runtime validation objects into static TypeScript types. The current stable version is `2.0.0`, with recent releases focusing on supporting Zod v4 and improving the handling of complex type structures, especially recursion. Releases appear to be feature-driven, with new minor versions adding capabilities and major versions introducing breaking changes, particularly around Zod compatibility and internal API improvements. Key differentiators include its ability to generate TypeScript AST nodes directly for programmatic manipulation, robust support for recursive types through an auxiliary type system, and configurable output (e.g., 'input' vs. 'output' types for schemas using transformations or pipes). It also supports JSDoc comments from Zod's `.describe()` method, making generated types more descriptive. This library is crucial for projects aiming to maintain type safety and reduce boilerplate by deriving types directly from Zod validation logic.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates converting complex Zod object schemas, including nested objects, arrays, and recursive structures, into TypeScript type aliases and printing them, showing how auxiliary types are generated for recursion.

import { z } from 'zod';
import { zodToTs, createAuxiliaryTypeStore, createTypeAlias, printNode } from 'zod-to-ts';

const CategorySchema = z.object({
  name: z.string(),
  subcategories: z.lazy(() => z.array(CategorySchema)),
});

const UserSchema = z.object({
  username: z.string().describe('User\'s unique identifier'),
  age: z.number().int().positive(),
  roles: z.array(z.literal('admin').or(z.literal('editor')).or(z.literal('viewer'))),
  inventory: z.object({
    name: z.string().min(1),
    itemId: z.number().int().positive(),
    quantity: z.number().int().min(0).optional(),
  }).array().describe('List of user\'s owned items'),
  favoriteCategory: CategorySchema,
});

const auxiliaryTypeStore = createAuxiliaryTypeStore();
const { node: userNode } = zodToTs(UserSchema, { auxiliaryTypeStore });

const userTypeAlias = createTypeAlias(userNode, 'User');
const userTypeString = printNode(userTypeAlias);
console.log('--- User Type ---');
console.log(userTypeString);

console.log('\n--- Auxiliary Types (for recursion) ---');
// Extract and print auxiliary types if any (e.g., for CategorySchema recursion)
const auxiliaryTypePreamble = Array.from(auxiliaryTypeStore.definitions.values())
  .map((definition) => printNode(definition.node))
  .join('\n');
console.log(auxiliaryTypePreamble);

view raw JSON →