How auxiliary types and auxiliaryTypeStore work
mainRecursive schemas (e.g., a category containing an array of categories) cannot be represented by a single type declaration. zod-to-ts uses an auxiliaryTypeStore to manage these helper types.
When a recursive or complex type is encountered, zodToTs returns a reference node (e.g., Auxiliary_0) and stores the actual type definition in the auxiliaryTypeStore. To generate a complete file, you must extract the definitions from the store and prepend them to your main type declaration.
import { z } from 'zod'
import { createAuxiliaryTypeStore, zodToTs, createTypeAlias, printNode } from 'zod-to-ts'
const Category = z.object({
name: z.string(),
get subcategories() {
return z.array(Category)
}
})
const auxiliaryTypeStore = createAuxiliaryTypeStore()
const { node } = zodToTs(Category, { auxiliaryTypeStore })
// 1. Extract all auxiliary definitions as a string preamble
const auxiliaryTypePreamble = auxiliaryTypeStore.definitions
.values()
.toArray()
.map((definition) => printNode(definition.node))
.join('\n')
// 2. Create the main type alias
const categoryTypeAlias = createTypeAlias(node, 'Category')
const categoryType = printNode(categoryTypeAlias)
// 3. Combine them
const outputFile = `${auxiliaryTypePreamble}\n${categoryType}`
console.log(outputFile)