The value to convert to a schema
Configuration options for schema generation
Optional
_currentDepth?: numberCurrent depth (internal)
Optional
allowMixedArrays?: booleanWhether to allow mixed types in arrays (default: true)
Optional
literalPrimitives?: booleanIf true
, use z.literal()
for primitive values instead of type schemas
Optional
literalRegExp?: booleanIf true
, treat RegExp
literals as RegExp
literals; otherwise treat
as strings and attempt match
Optional
maxDepth?: numberMaximum nesting depth to prevent stack overflow (default: 10)
Optional
strict?: booleanIf true
, will disallow unknown properties in objects
Internal WeakSet for circular reference detection
A Zod schema that validates values matching the input's structure
// Primitive types
valueToSchema('hello'); // z.string()
valueToSchema(42); // z.number()
valueToSchema(true); // z.boolean()
// Objects
valueToSchema({ name: 'John', age: 30 });
// z.object({ name: z.string(), age: z.number() })
// Arrays
valueToSchema(['a', 'b', 'c']); // z.array(z.string())
valueToSchema([1, 'mixed']); // z.array(z.union([z.number(), z.string()]))
// Nested structures
valueToSchema({ users: [{ name: 'John' }] });
// z.object({ users: z.array(z.object({ name: z.string() })) })
Recursively converts an arbitrary value to a Zod v4 schema that would validate values with the same structure.
This function analyzes the runtime value and generates a corresponding Zod schema that captures the value's structure and type information. It handles primitives, objects, arrays, functions, and various built-in types, with support for circular reference detection.