Zod logo

Zod 核心

此子包导出了 Zod 和 Zod Mini 使用的核心类和工具。它不打算被直接使用;而是设计为可被其他包扩展。它实现了:

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

import * as 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

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

内部机制

🌐 Internals

所有 zod/v4/core 子类只包含一个属性:_zod。这个属性是一个包含 internals 模式的对象。目标是使 zod/v4/core 尽可能可扩展且不带主观偏向。其他库可以在这些类的基础上“构建自己的 Zod”,而不会被 zod/v4/core 混乱界面。有关如何扩展这些类的示例,请参阅 zodzod/mini 的实现。

🌐 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 and zod/mini for examples of how to extend these classes.

_zod 内部属性包含一些显著的属性:

🌐 The _zod internals property contains some notable properties:

  • .def — 模式的定义:这是你传入类构造函数以创建实例的对象。它完全描述了该模式,并且可以被 JSON 序列化。
    • .def.type — 一个表示模式类型的字符串,例如 "string""object""array" 等。
    • .def.checks — 在解析后由模式执行的一组检查
  • .input — 一个虚拟属性,用于“存储”模式的推断输入类型
  • .output — 一个虚拟属性,用于“存储”模式的推断输出类型
  • .run() — 模式的内部解析器实现。

如果你正在实现一个必须遍历 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 模式都包含一个 checks 数组。这些执行解析后的精炼(有时也会进行变更),但 不会影响 推断出的类型。

🌐 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 内部属性包含一些显著的属性:

🌐 The _zod internals property contains some notable properties:

  • .def — 检查的定义:这是你传递给类构造函数以创建检查的对象。它完全描述了检查,并且可以被 JSON 序列化。
    • .def.check — 一个表示检查类型的字符串,例如 "min_length""less_than""string_format" 等。
  • .check() — 包含多选的验证逻辑。

zod/v4/core 导出了一些执行常见改进的子类。所有第一方子类都作为名为 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

  • zod 包实现了 $ZodError 的一个子类,称为 ZodError,并提供了一些附加的便利方法。
  • zod/mini 子包直接使用 $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