Zod
Zod is a TypeScript-first schema declaration and validation library that provides static type inference, ensuring runtime data matches compile-time types. The current stable version is 4.3.6, with frequent patch and minor releases addressing bug fixes, performance improvements, and new features like `z.fromJSONSchema()`.
Common errors
-
ZodError: [ { "code": "invalid_type", "expected": "date", "received": "string", "path": [ "myDate" ], "message": "Expected date, received string" } ]cause Attempting to parse a date string directly with `z.date()` instead of a `Date` object.fixChange the schema to `z.coerce.date()` to enable automatic string-to-Date conversion upon parsing. -
ZodError: [ { "code": "unrecognized_keys", "keys": [ "extraField" ] } ]cause Input object contains keys not defined in a `z.object()` schema that is in default 'strict' mode.fixIf extra keys should be allowed, modify your schema to `z.object({ /* ... */ }).passthrough()`. If they should be ignored, use `z.object({ /* ... */ }).strip()`. -
TypeError: Cannot read properties of undefined (reading 'parse')
cause The Zod schema variable is `undefined` at the point of calling `.parse()` or `.safeParse()`, typically due to an incorrect import or variable scope issue.fixVerify that `import * as z from 'zod';` is correctly placed and that your schema variable is defined and accessible where `.parse()` is called. -
Type 'string' is not assignable to type 'ZodObject<...>' (TypeScript error)
cause Attempting to use a Zod schema directly where its inferred type is expected, or passing data to a function that expects a schema instance without calling a parsing method.fixAlways call `.parse(data)` or `.safeParse(data)` on your schema instance to validate and extract the typed value.
Warnings
- deprecated The `message` property directly on individual Zod schema validators (e.g., `z.string().min(1, { message: '...' })`) has been deprecated.
- gotcha `z.date()` expects a `Date` object, not a date string. Passing a string will typically result in an 'Invalid date' error unless it can be reliably converted by JavaScript's `Date` constructor.
- gotcha By default, `z.object()` schemas are 'strict', meaning they will strip or error on unknown keys in the input object. This can lead to unexpected data loss or validation failures.
- gotcha `z.refine()` is always synchronous. For asynchronous validations (e.g., checking uniqueness against a database), it will not correctly await Promises.
Install
-
npm install zod -
yarn add zod -
pnpm add zod
Imports
- z
const z = require('zod')import * as z from 'zod'
Quickstart
import * as z from "zod";
const UserSchema = z.object({
id: z.string().uuid(),
name: z.string().min(1),
email: z.string().email(),
age: z.number().int().positive().optional(),
});
type User = z.infer<typeof UserSchema>;
const validUser: User = UserSchema.parse({
id: "a1b2c3d4-e5f6-7890-1234-567890abcdef",
name: "Alice",
email: "alice@example.com",
});
console.log("Parsed user:", validUser);
// Expected output: Parsed user: { id: '...', name: 'Alice', email: 'alice@example.com' }
try {
UserSchema.parse({
id: "invalid-uuid",
name: "",
email: "not-an-email",
});
} catch (error) {
console.error("Validation error:\n", error);
// Expected output (abbreviated): Validation error:
ZodError: [
{ code: 'invalid_string', validation: 'uuid', ... },
{ code: 'too_small', minimum: 1, ... },
{ code: 'invalid_string', validation: 'email', ... }
]
}