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

schema definitions

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

Access object shape with .shape property

Use Dog.shape.name to access internal schemas of object. In Zod Mini use Dog.def.shape.name.

Create enum from object keys with .keyof()

Use Dog.keyof() to create ZodEnum schema from object keys. In Zod Mini use z.keyof(Dog).

Catchall schema for unknown keys

Use .catchall(schema) on object to validate unrecognized keys: z.object({ name: z.string() }).catchall(z.string()). In Zod Mini use z.catchall(object, schema).

Coercion with z.coerce converts input types

Use z.coerce instead of z to coerce input data to the appropriate type. z.coerce.string(), z.coerce.number(), z.coerce.boolean(), and z.coerce.bigint() use the built-in constructors: String(value), Number(value), Boolean(value), BigInt(value). The input type is unknown by default; specify it with a generic parameter like z.coerce.number<number>().

Boolean coercion with z.coerce.boolean() uses truthiness

z.coerce.boolean() coerces any truthy value to true and any falsy value to false. For example, z.coerce.boolean().parse('tuna') returns true, and z.coerce.boolean().parse('false') also returns true because the string 'false' is truthy. z.coerce.boolean().parse(0) returns false.

Date validation with z.date()

Use z.date() to validate Date instances. z.date().safeParse(new Date()) returns success: true, but z.date().safeParse('2022-01-12T06:15:00.000Z') returns success: false. Customize error message with z.date({ error: issue => issue.input === undefined ? 'Required' : 'Invalid date' }).

Date constraints with min and max

Constrain dates with z.date().min(new Date('1900-01-01'), { error: 'Too old!' }) and z.date().max(new Date(), { error: 'Too young!' }).

Optional schema with z.optional()

Use z.optional(schema) or schema.optional() to make a schema optional, allowing undefined inputs. Returns ZodOptional instance. Extract inner schema with unwrap() method (Zod) or .def.innerType (Zod Mini).

Exact optional with z.exactOptional()

Use z.exactOptional(schema) or schema.exactOptional() to allow absent key without allowing explicit undefined, per TypeScript's exactOptionalPropertyTypes. Example: z.object({ name: z.string().exactOptional() }) allows {} and { name: 'yoda' } but not { name: undefined }.

Nullable schema with z.nullable()

Use z.nullable(schema) or schema.nullable() to make a schema nullable, allowing null inputs. Returns ZodNullable instance. Extract inner schema with unwrap() method (Zod) or .def.innerType (Zod Mini).

Nullish schema with z.nullish()

Use z.nullish(schema) to make a schema both optional and nullable, allowing both undefined and null inputs.

Any and unknown types in Zod

Use z.any() for inferred type 'any' and z.unknown() for inferred type 'unknown'. As object properties, their keys are required like { a: any } in TypeScript. z.object({ a: z.any() }).parse({}) fails, but z.object({ a: z.any().optional() }).parse({}) passes.

Never type with z.never()

Use z.never() for a schema where no value will pass validation. Inferred type is 'never'.

Object schema definition

Use z.object({ name: z.string(), age: z.number() }) to define object types. All properties are required by default. Properties can be made optional with .optional() method.

Strict object schema with z.strictObject()

Use z.strictObject({ name: z.string() }) to throw error when unknown keys are found. Regular z.object() strips unrecognized keys by default.

Loose object schema with z.looseObject()

Use z.looseObject({ name: z.string() }) to allow unknown keys to pass through. Regular z.object() strips unrecognized keys by default.

Extend object schema with additional fields

Use Dog.extend({ breed: z.string() }) to add fields to object schema. Can overwrite existing fields. In Zod Mini use z.extend(Dog, { breed: z.string() }). Alternative: use spread syntax with z.object({ ...Dog.shape, breed: z.string() }).

Safe extend with .safeExtend()

Use .safeExtend() instead of .extend() to prevent overwriting with non-assignable schemas. Result inferred type extends original. Use .safeExtend() with schemas carrying refinements (regular .extend() throws error with refinements).

Pick keys from object schema with .pick()

Use Recipe.pick({ title: true }) to create new schema with only certain keys. In Zod Mini use z.pick(Recipe, { title: true }).

Omit keys from object schema with .omit()

Use Recipe.omit({ id: true }) to create new schema excluding certain keys. In Zod Mini use z.omit(Recipe, { id: true }).

Make all properties optional with .partial()

Use Recipe.partial() to make all fields optional. Use Recipe.partial({ ingredients: true }) to make only certain properties optional. In Zod Mini use z.partial(Recipe) or z.partial(Recipe, { ingredients: true }).

Exact partial with .exactPartial()

Use Recipe.exactPartial() like .partial() but wraps each field in exactOptional() instead of optional(). In Zod Mini use z.exactPartial(Recipe).

Deep partial for nested structures

Use z.deepPartial(Post) to recursively make all properties optional through arrays, tuples, unions, records, and wrappers. Original schema not modified. Result is still ZodObject so .shape and .extend() keep working. Discriminated unions degrade to plain union.

Make properties required with .required()

Use Recipe.required() to make all properties required. Use Recipe.required({ description: true }) to make only certain properties required. In Zod Mini use z.required(Recipe) or z.required(Recipe, { description: true }).

Recursive object schemas using getters

Define recursive types using getter functions: const Category = z.object({ name: z.string(), get subcategories() { return z.array(Category) } }). Use for self-referential types and mutually recursive types. Passing cyclical data causes infinite loop.

Fix recursive type inference errors with annotations

When recursive getter triggers 'implicitly has return type any', add type annotation: get subactivities(): z.ZodNullable<z.ZodArray<typeof Activity>> { return z.nullable(z.array(Activity)) }.

Array schema definition

Use z.array(z.string()) or z.string().array() to define array schemas. Access element schema with unwrap() (Zod) or .def.element (Zod Mini).

Array constraints and validation

Array validations: z.array(z.string()).nonempty() requires at least 1 item, .min(5) requires 5+ items, .max(5) allows 5 or fewer, .length(5) exactly 5 items. In Zod Mini use .check(z.minLength(1)), .check(z.minLength(5)), .check(z.maxLength(5)), .check(z.length(5)).

Tuple schema for fixed-length arrays

Use z.tuple([z.string(), z.number(), z.boolean()]) to validate fixed-length arrays with different schema per index. Add variadic argument: z.tuple([z.string()], z.number()) for [string, ...number[]].

Union schema for logical OR

Use z.union([z.string(), z.number()]) to validate string or number. Zod checks options in order and returns first match. Extract options with .options property (Zod) or .def.options (Zod Mini).

Exclusive union with z.xor()

Use z.xor([z.string(), z.number()]) to validate exactly one option matches. Fails if zero options or multiple options match. Useful for mutual exclusivity. Failed issues have inclusive: false and matches array listing option indices.

Discriminated union for efficient parsing

Use z.discriminatedUnion('status', [z.object({ status: z.literal('success'), data: z.string() }), z.object({ status: z.literal('failed'), error: z.string() })]) for efficient parsing of large unions. Discriminator prop should be literal, enum, null, or undefined. Supports nesting of discriminated unions.

Intersection schema for logical AND

Use z.intersection(a, b) for logical AND between schemas. Useful for intersecting object types. For object merging, prefer A.extend(B) over z.intersection() since .extend() returns ZodObject with methods like pick and omit, while z.intersection() returns ZodIntersection.

Record schema for key-value validation

Use z.record(z.string(), z.string()) to validate Record<string, string>. Key schema must be assignable to string | number | symbol. With z.enum() key schema, exhaustively checks all enum values as keys. Use z.partialRecord() to skip exhaustiveness checks.

Numeric record keys validation

In z.record(z.number(), z.string()), number schema validates numeric string keys. Example: z.record(z.int().step(1).min(0).max(10), z.string()) validates keys 0-10 as integers, rejecting '1.5' or 'abc'.

Loose record schema with z.looseRecord()

Use z.looseRecord(z.string().regex(/_phone$/), z.e164()) to pass through non-matching keys unchanged. Useful with intersections for pattern properties like multiple phone fields.

Map schema for Map<K, V> validation

Use z.map(z.string(), z.number()) to validate Map instances. Access with .nonempty(), .min(5), .max(5), .size(5) methods. In Zod Mini use .check(z.minSize(1)), .check(z.minSize(5)), .check(z.maxSize(5)), .check(z.size(5)).

Set schema for Set<T> validation

Use z.set(z.number()) to validate Set instances. Constrain with .nonempty(), .min(5), .max(5), .size(5) methods. In Zod Mini use .check(z.minSize(1)), .check(z.minSize(5)), .check(z.maxSize(5)), .check(z.size(5)).

Instanceof schema for class instance validation

Use z.instanceof(Test) to check input is instance of class Test. Works with built-in classes like RegExp, URL, Error. Example: z.instanceof(URL).parse(new URL('https://example.com')) passes.

Property validation on class instances

Use z.instanceof(URL).check(z.property('protocol', z.literal('https:'))) to validate properties. z.property() works with any data type but most useful with instanceof. Example: z.string().check(z.property('length', z.number().min(10))) validates string length >= 10.

default() sets value for undefined input

Use `.default(value)` to set a default value for a schema. If input is `undefined`, the default value is returned. The default value must be assignable to the output type. Alternatively, pass a function which will be re-executed whenever a default value is needed: `.default(Math.random)`.

prefault() sets pre-parse default value

Use `.prefault(value)` to define a prefault ('pre-parse default') value. If input is `undefined`, the prefault value will be parsed instead, not short-circuited. The prefault value must be assignable to the input type of the schema. This is useful for applying mutating refinements to the prefault value. Example: `z.string().trim().toUpperCase().prefault(" tuna ")` parses undefined to "TUNA".

brand() creates nominal types

Use `.brand<"BrandName">()` to simulate nominal typing. This attaches a brand to the schema's inferred type, preventing plain data structures from being assignable to the branded type. You must parse data with the schema to get branded data. By default, only the output type is branded. In Zod 4.2+, pass a second generic: `.brand<"Cat", "out">()` (output branded, default), `.brand<"Cat", "in">()` (input branded), or `.brand<"Cat", "inout">()` (both branded).

brand() is static-only construct

Branded types do not affect the runtime result of `.parse()`. Branding is a static-only TypeScript construct for type safety.

readonly() marks schema as readonly

Use `.readonly()` to mark a schema as readonly. The inferred type is marked as `readonly`. In TypeScript, this only affects objects, arrays, tuples, `Set`, and `Map`. Inputs are parsed like normal, then the result is frozen with `Object.freeze()` to prevent modifications. In Zod Mini, use `z.readonly(schema)`.

z.json() validates JSON-encodable values

Use `z.json()` to validate any JSON-encodable value. This returns a union schema of string, number, boolean, null, array of JSON values, and record of string keys to JSON values.

z.function() for Zod-validated functions

Zod provides `z.function()` to define Zod-validated functions. Syntax: `z.function({ input: [z.string()], output: z.number() })`. The `input` must be an array or ZodTuple. The `output` field is optional if only validating inputs.

function schema implement() method

Function schemas have an `.implement(fn)` method which accepts a function and returns a new function that automatically validates its inputs and outputs. This function will throw a `ZodError` if input or output is invalid. Use `.implementAsync(asyncFn)` to create an async function.

Give your agent this brain