Zod logo

Zod 核心

此子包导出 zod/v4zod/v4-mini 使用的核心类和实用程序。它不打算直接使用;它的设计初衷是供其他包扩展。它实现了:

¥This sub-package exports the core classes and utilities that are consumed by zod/v4 and zod/v4-mini. It is not intended to be used directly; instead it's designed to be extended by other packages. It implements:

import { z } from "zod/v4/core";
 
// the base class for all Zod schemas
z.$ZodType;
 
// subclasses of $ZodType that implement common parsers
z.$ZodString
z.$ZodObject
z.$ZodArray
// ...
 
// the base class for all Zod checks
z.$ZodCheck;
 
// subclasses of $ZodCheck that implement common checks
z.$ZodCheckMinLength
z.$ZodCheckMaxLength
 
// the base class for all Zod errors
z.$ZodError;
 
// issue formats (types only)
{} as z.$ZodIssue;
 
// utils
z.util.isValidJWT(...);

模式

¥Schemas

所有 Zod 模式的基类都是 $ZodType。它接受两个泛型参数:OutputInput

¥The base class for all Zod schemas is $ZodType. It accepts two generic parameters: Output and Input.

export class $ZodType<Output = unknown, Input = unknown> {
  _zod: { /* internals */}
}

zod/v4/core 导出了一些实现常用解析器的子类。所有第一方子类的联合导出为 z.$ZodTypes

¥zod/v4/core exports a number of subclasses that implement some common parsers. A union of all first-party subclasses is exported as z.$ZodTypes.

export type $ZodTypes =
  | $ZodString
  | $ZodNumber
  | $ZodBigInt
  | $ZodBoolean
  | $ZodDate
  | $ZodSymbol
  | $ZodUndefined
  | $ZodNullable
  | $ZodNull
  | $ZodAny
  | $ZodUnknown
  | $ZodNever
  | $ZodVoid
  | $ZodArray
  | $ZodObject
  | $ZodUnion
  | $ZodIntersection
  | $ZodTuple
  | $ZodRecord
  | $ZodMap
  | $ZodSet
  | $ZodLiteral
  | $ZodEnum
  | $ZodPromise
  | $ZodLazy
  | $ZodOptional
  | $ZodDefault
  | $ZodTemplateLiteral
  | $ZodCustom
  | $ZodTransform
  | $ZodNonOptional
  | $ZodReadonly
  | $ZodNaN
  | $ZodPipe
  | $ZodSuccess
  | $ZodCatch
  | $ZodFile;

内部机制

¥Internals

所有 zod/v4/core 子类仅包含一个属性:_zod。此属性是一个包含模式内部结构的对象。目标是使 zod/v4/core 尽可能易于扩展且不带任何偏见。其他库可以在这些类之上使用 "构建自己的 Zod",而不会使 zod/v4/core 弄乱界面。有关核心子库内容的更多信息,请参阅 zod/v4 页面。

¥All zod/v4/core subclasses only contain a single property: _zod. This property is an object containing the schemas internals. The goal is to make zod/v4/core as extensible and unopinionated as possible. Other libraries can "build their own Zod" on top of these classes without zod/v4/core cluttering up the interface. Refer to the implementations of zod/v4 and zod/v4-mini for examples of how to extend these classes.

_zod internals 属性包含一些值得注意的属性:

¥The _zod internals property contains some notable properties:

  • .def — 模式的定义:这是你传递给类的构造函数以创建实例的对象。它完整地描述了模式,并且可以 JSON 序列化。

    ¥.def — The schema's definition: this is the object you pass into the class's constructor to create an instance. It completely describes the schema, and it's JSON-serializable.

    • .def.type — 表示架构类型的字符串,例如 "string""object""array" 等。

      ¥.def.type — A string representing the schema's type, e.g. "string", "object", "array", etc.

    • .def.checks — 解析后由架构执行的检查数组。

      ¥.def.checks — An array of checks that are executed by the schema after parsing.

  • .input — 一个虚拟属性,用于 "stores" 架构推断的输入类型。

    ¥.input — A virtual property that "stores" the schema's inferred input type.

  • .output — 一个虚拟属性,用于 "stores" 架构推断的输出类型。

    ¥.output — A virtual property that "stores" the schema's inferred output type.

  • .run() — 模式的内部解析器实现。

    ¥.run() — The schema's internal parser implementation.

如果你正在实现一个必须遍历 Zod 模式的工具(例如,代码生成器),则可以将任何模式转换为 $ZodTypes,并使用 def 属性来区分这些类。

¥If you are implementing a tool (say, a code generator) that must traverse Zod schemas, you can cast any schema to $ZodTypes and use the def property to discriminate between these classes.

export function walk(_schema: z.$ZodType) {
  const schema = _schema as z.$ZodTypes;
  const def = schema._zod.def;
  switch (def.type) {
    case "string": {
      // ...
      break;
    }
    case "object": {
      // ...
      break;
    }
  }
}

$ZodString 有许多子类,它们实现了各种字符串格式。这些导出为 z.$ZodStringFormatTypes

¥There are a number of subclasses of $ZodString that implement various string formats. These are exported as z.$ZodStringFormatTypes.

export type $ZodStringFormatTypes =
  | $ZodGUID
  | $ZodUUID
  | $ZodEmail
  | $ZodURL
  | $ZodEmoji
  | $ZodNanoID
  | $ZodCUID
  | $ZodCUID2
  | $ZodULID
  | $ZodXID
  | $ZodKSUID
  | $ZodISODateTime
  | $ZodISODate
  | $ZodISOTime
  | $ZodISODuration
  | $ZodIPv4
  | $ZodIPv6
  | $ZodCIDRv4
  | $ZodCIDRv6
  | $ZodBase64
  | $ZodBase64URL
  | $ZodE164
  | $ZodJWT

解析

¥Parsing

由于 Zod Core 模式类没有方法,因此存在用于解析数据的顶层函数。

¥As the Zod Core schema classes have no methods, there are top-level functions for parsing data.

import * as z from "zod/v4/core";
 
const schema = new z.$ZodString({ type: "string" });
z.parse(schema, "hello");
z.safeParse(schema, "hello");
await z.parseAsync(schema, "hello");
await z.safeParseAsync(schema, "hello");

检查

¥Checks

每个 Zod 模式都包含一个检查数组。它们执行解析后细化(偶尔会发生修改),但不影响推断的类型。

¥Every Zod schema contains an array of checks. These perform post-parsing refinements (and occasionally mutations) that do not affect the inferred type.

const schema = z.string().check(z.email()).check(z.min(5));
// => $ZodString
 
schema._zod.def.checks;
// => [$ZodCheckEmail, $ZodCheckMinLength]

所有 Zod 检查的基类都是 $ZodCheck。它接受单个泛型参数 T

¥The base class for all Zod checks is $ZodCheck. It accepts a single generic parameter T.

export class $ZodCheck<in T = unknown> {
  _zod: { /* internals */}
}

_zod internals 属性包含一些值得注意的属性:

¥The _zod internals property contains some notable properties:

  • .def — 检查的定义:这是你传递给类的构造函数以创建检查的对象。它完整地描述了检查,并且可以 JSON 序列化。

    ¥.def — The check's definition: this is the object you pass into the class's constructor to create the check. It completely describes the check, and it's JSON-serializable.

    • .def.check — 表示检查类型的字符串,例如 "min_lenth""less_than""string_format" 等。

      ¥.def.check — A string representing the check's type, e.g. "min_lenth", "less_than", "string_format", etc.

  • .check() — 包含检查的验证逻辑。

    ¥.check() — Contains the check's validation logic.

zod/v4/core 导出了一些执行常用细化操作的子类。所有第一方子类都导出为名为 z.$ZodChecks 的联合体。

¥zod/v4/core exports a number of subclasses that perform some common refinements. All first-party subclasses are exported as a union called z.$ZodChecks.

export type $ZodChecks =
  | $ZodCheckLessThan
  | $ZodCheckGreaterThan
  | $ZodCheckMultipleOf
  | $ZodCheckNumberFormat
  | $ZodCheckBigIntFormat
  | $ZodCheckMaxSize
  | $ZodCheckMinSize
  | $ZodCheckSizeEquals
  | $ZodCheckMaxLength
  | $ZodCheckMinLength
  | $ZodCheckLengthEquals
  | $ZodCheckProperty
  | $ZodCheckMimeType
  | $ZodCheckOverwrite
  | $ZodCheckStringFormat

你可以使用 ._zod.def.check 属性来区分这些类。

¥You can use the ._zod.def.check property to discriminate between these classes.

const check = {} as z.$ZodChecks;
const def = check._zod.def;
 
switch (def.check) {
  case "less_than":
  case "greater_than":
    // ...
    break;
}

与模式类型一样,$ZodCheckStringFormat 有许多子类,它们实现了各种字符串格式。

¥As with schema types, there are a number of subclasses of $ZodCheckStringFormat that implement various string formats.

export type $ZodStringFormatChecks =
  | $ZodCheckRegex
  | $ZodCheckLowerCase
  | $ZodCheckUpperCase
  | $ZodCheckIncludes
  | $ZodCheckStartsWith
  | $ZodCheckEndsWith
  | $ZodGUID
  | $ZodUUID
  | $ZodEmail
  | $ZodURL
  | $ZodEmoji
  | $ZodNanoID
  | $ZodCUID
  | $ZodCUID2
  | $ZodULID
  | $ZodXID
  | $ZodKSUID
  | $ZodISODateTime
  | $ZodISODate
  | $ZodISOTime
  | $ZodISODuration
  | $ZodIPv4
  | $ZodIPv6
  | $ZodCIDRv4
  | $ZodCIDRv6
  | $ZodBase64
  | $ZodBase64URL
  | $ZodE164
  | $ZodJWT;

使用嵌套的 switch 来区分不同的字符串格式检查。

¥Use a nested switch to discriminate between the different string format checks.

const check = {} as z.$ZodChecks;
const def = check._zod.def;
 
switch (def.check) {
  case "less_than":
  case "greater_than":
  // ...
  case "string_format":
    {
      const formatCheck = check as z.$ZodStringFormatChecks;
      const formatCheckDef = formatCheck._zod.def;
 
      switch (formatCheckDef.format) {
        case "email":
        case "url":
          // do stuff
      }
    }
    break;
}

你会注意到其中一些字符串格式检查与上面的字符串格式类型重叠。这是因为这些类同时实现了 $ZodCheck$ZodType 接口。也就是说,它们既可以用作检查,也可以用作类型。在这些情况下,._zod.parse(模式解析器)和 ._zod.check(检查验证)都会在解析过程中执行。实际上,该实例被添加到其自己的 checks 数组的前面(尽管它实际上并不存在 ._zod.def.checks 中)。

¥You'll notice some of these string format checks overlap with the string format types above. That's because these classes implement both the $ZodCheck and $ZodType interfaces. That is, they can be used as either a check or a type. In these cases, both ._zod.parse (the schema parser) and ._zod.check (the check validation) are executed during parsing. In effect, the instance is prepended to its own checks array (though it won't actually exist in ._zod.def.checks).

// as a type
z.email().parse("user@example.com");
 
// as a check
z.string().check(z.email()).parse("user@example.com")

错误

¥Errors

Zod 中所有错误的基类都是 $ZodError

¥The base class for all errors in Zod is $ZodError.

出于性能原因,$ZodError 不扩展内置的 Error 类!因此使用 instanceof Error 将返回 false

¥For performance reasons, $ZodError does not extend the built-in Error class! So using instanceof Error will return false.

  • zod/v4 包实现了 $ZodError 的子类 ZodError,并添加了一些便捷的方法。

    ¥The zod/v4 package implements a subclass of $ZodError called ZodError with some additional convenience methods.

  • zod/v4-mini 子包直接使用 $ZodError

    ¥The zod/v4-mini sub-package directly uses $ZodError

export class $ZodError<T = unknown> implements Error {
 public issues: $ZodIssue[];
}

问题

¥Issues

issues 属性对应于一个 $ZodIssue 对象数组。所有问题都扩展了 z.$ZodIssueBase 接口。

¥The issues property corresponds to an array of $ZodIssue objects. All issues extend the z.$ZodIssueBase interface.

export interface $ZodIssueBase {
  readonly code?: string;
  readonly input?: unknown;
  readonly path: PropertyKey[];
  readonly message: string;
}

Zod 定义了以下问题子类型:

¥Zod defines the following issue subtypes:

export type $ZodIssue =
  | $ZodIssueInvalidType
  | $ZodIssueTooBig
  | $ZodIssueTooSmall
  | $ZodIssueInvalidStringFormat
  | $ZodIssueNotMultipleOf
  | $ZodIssueUnrecognizedKeys
  | $ZodIssueInvalidUnion
  | $ZodIssueInvalidKey
  | $ZodIssueInvalidElement
  | $ZodIssueInvalidValue
  | $ZodIssueCustom;

有关每种类型的详细信息,请参阅 实现

¥For details on each type, refer to the implementation.

On this page