new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Zod · all subjects

advanced schema types

30 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

z.array() for array validation

z.array(schema) or schema.array() defines array schemas. Access inner element schema with .unwrap() in Zod or .def.element in Zod Mini.

Array length validations

z.array(z.string()).nonempty() requires at least 1 item. .min(n) requires n or more items. .max(n) requires n or fewer items. .length(n) requires exactly n items. In Zod Mini, use .check() with z.minLength(), z.maxLength(), z.length().

z.tuple() for fixed-length arrays with typed elements

z.tuple([z.string(), z.number(), z.boolean()]) creates a tuple with different schemas for each index, producing type [string, number, boolean]. To add variadic rest: z.tuple([z.string()], z.number()) produces [string, ...number[]].

z.union() for OR types

z.union([z.string(), z.number()]) creates a union type string | number. Zod checks input against each option in order and returns the first match. Access options with .options in Zod or .def.options in Zod Mini.

z.xor() for exclusive union (exactly one match)

z.xor([z.string(), z.number()]) creates an exclusive union where exactly one option must match. Fails if zero options match OR if multiple options match. Useful for mutual exclusivity between options.

z.discriminatedUnion() for efficient union discrimination

z.discriminatedUnion(discriminatorKey, [option1, option2]) uses a discriminator key for efficient parsing instead of checking all options. Each option should be an object schema with the discriminator property as a literal value. More efficient than regular z.union() for large unions. Supports nested discriminated unions.

z.intersection() for AND types

z.intersection(a, b) creates an intersection type A & B. Useful for intersecting unions to narrow types. For merging object schemas, prefer .extend() instead, as z.intersection() returns ZodIntersection lacking object methods like pick and omit.

z.record() for Record types

z.record(keySchema, valueSchema) validates Record<K, V> types. Key schema must be assignable to string | number | symbol. Example: z.record(z.string(), z.string()) validates Record<string, string>. Number keys in records validate numeric strings.

z.record() with enum keys requires all values

When passing z.enum() as the first argument to z.record(), Zod exhaustively checks that all enum values exist as keys in the input. For partial key sets, use z.partialRecord() instead.

z.partialRecord() for partial enum keys

z.partialRecord(keySchema, valueSchema) skips exhaustiveness checks that z.record() normally runs with z.enum() and z.literal() key schemas. Use for partial key sets.

z.looseRecord() passes through non-matching keys

z.looseRecord(keySchema, valueSchema) passes through keys that don't match the key schema unchanged instead of erroring. Useful with intersections to model multiple pattern properties.

z.map() for Map validation

z.map(keySchema, valueSchema) validates Map instances. Example: z.map(z.string(), z.number()) creates Map<string, number>. Supports .nonempty(), .min(n), .max(n), .size(n) constraints. In Zod Mini use .check() with z.minSize(), z.maxSize(), z.size().

z.set() for Set validation

z.set(elementSchema) validates Set instances. Example: z.set(z.number()) creates Set<number>. Supports .nonempty(), .min(n), .max(n), .size(n) constraints. In Zod Mini use .check() with z.minSize(), z.maxSize(), z.size().

z.instanceof() for class instance validation

z.instanceof(ClassName) checks that input is an instance of the specified class. Works with built-in classes: z.instanceof(RegExp), z.instanceof(URL), z.instanceof(Error).

z.property() validates object properties

z.property(propertyName, schema) validates a particular property of an object against a schema. Useful with z.instanceof(). Example: z.instanceof(URL).check(z.property('protocol', z.literal('https:'))). Works with any data type.

z.promise() is deprecated

z.promise() is deprecated. There are vanishingly few valid uses cases for a Promise schema. If you suspect a value might be a Promise, simply await it before parsing with Zod.

z.function() defines Zod-validated functions

Use z.function() to define validated functions: z.function({ input: [z.string()], output: z.number() }). The input must be an array or ZodTuple. Inferred type is (input: string) => number. Can omit output field to validate only inputs.

function schema .implement() method

Call .implement() on a function schema to create a function that automatically validates inputs and outputs. Example: MyFunction.implement((input) => input.trim().length) returns a function that throws ZodError if validation fails.

function schema .implementAsync() for async functions

Use .implementAsync() to create an async function from a function schema. Example: MyFunction.implementAsync(async (input) => input.trim().length) returns a Promise.

z.custom() for third-party types

Use z.custom<Type>() to create a schema for any TypeScript type not covered by built-in schemas. Pass a validation function as first argument: z.custom<Decimal>((val) => Decimal.isDecimal(val)). For class instances, prefer z.instanceof(); for template literals, prefer z.templateLiteral().

z.custom() without validation function

If you don't provide a validation function to z.custom<Type>(), Zod will allow any value. This can be dangerous and should generally be avoided.

z.registry() creates typed metadata registry

Use z.registry<T>() to create a schema registry that associates schemas with strongly-typed metadata. Add schemas with myRegistry.add(schema, metadata) and retrieve with myRegistry.get(schema).

z.globalRegistry accepts JSON Schema metadata

Zod exports a global registry z.globalRegistry that accepts JSON Schema-compatible metadata fields: id, title, description, examples, and additional custom properties.

.meta() method adds schema to globalRegistry

The .meta() method is an immutable method that adds metadata to z.globalRegistry and returns a clone of the schema. Example: z.string().meta({ id: 'email_address', title: 'Email address', description: 'Provide your email', examples: ['naomie@example.com'] })

.describe() deprecated in favor of .meta()

For compatibility with Zod 3, .describe() is still available but .meta() is preferred. z.string().describe('An email address') is equivalent to z.string().meta({ description: 'An email address' }).

Recursive object schema using getter pattern

Define recursive types using a getter function inside z.object(). Example: const Category = z.object({ name: z.string(), get subcategories(){ return z.array(Category) } }); type Category = z.infer<typeof Category>; // { name: string; subcategories: Category[] }

Mutually recursive schemas use getter pattern

Define mutually recursive types by using getter functions that reference other schemas. Example: const User = z.object({ email: z.email(), get posts(){ return z.array(Post) } }); const Post = z.object({ title: z.string(), get author(){ return User } });

Recursive schemas support all schema methods in Zod 4

Unlike Zod 3, recursive schemas defined with getter patterns are plain ZodObject instances and support all methods without type casting. Example: Post.pick({ title: true }), Post.partial(), Post.extend({ publishDate: z.date() })

z.discriminatedUnion() now supports unions and pipes

Discriminated unions support additional schema types: simple literals, union discriminators (z.literal('a') | z.literal('b')), and pipe discriminators (z.literal('fail').transform()). Example: z.discriminatedUnion('status', [z.object({ status: z.union([z.literal('bbb'), z.literal('ccc')]) })])

z.discriminatedUnion() schemas can be composed

Discriminated unions now compose—one discriminated union can be a member of another. Example: z.discriminatedUnion('status', [z.object({...}), z.discriminatedUnion('code', [...])])

Give your agent this brain