zod

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Zod Best Practices

Zod 最佳实践

Comprehensive schema validation guide for Zod 4 in TypeScript applications. Contains 43 rules across 8 categories, prioritized by impact to guide automated refactoring and code generation.
TypeScript应用中Zod 4的全面模式验证指南。包含8个类别共43条规则,按影响优先级排序,可指导自动化重构与代码生成。

When to Apply

适用场景

Reference these guidelines when:
  • Writing new Zod schemas
  • Choosing between parse() and safeParse()
  • Implementing type inference with z.infer
  • Handling validation errors for user feedback
  • Composing complex object schemas
  • Using refinements and transforms
  • Optimizing bundle size and validation performance
  • Reviewing Zod code for best practices
在以下场景中参考本指南:
  • 编写新的Zod模式
  • 在parse()和safeParse()之间做选择
  • 使用z.infer实现类型推断
  • 处理验证错误以提供用户反馈
  • 组合复杂对象模式
  • 使用refinements和transforms
  • 优化包体积与验证性能
  • 审查Zod代码是否符合最佳实践

Rule Categories by Priority

按优先级划分的规则类别

PriorityCategoryImpactPrefix
1Schema DefinitionCRITICAL
schema-
2Parsing & ValidationCRITICAL
parse-
3Type InferenceHIGH
type-
4Error HandlingHIGH
error-
5Object SchemasMEDIUM-HIGH
object-
6Schema CompositionMEDIUM
compose-
7Refinements & TransformsMEDIUM
refine-
8Performance & BundleLOW-MEDIUM
perf-
优先级类别影响程度前缀
1模式定义关键
schema-
2解析与验证关键
parse-
3类型推断
type-
4错误处理
error-
5对象模式中高
object-
6模式组合
compose-
7细化与转换
refine-
8性能与包体积中低
perf-

Quick Reference

快速参考

1. Schema Definition (CRITICAL)

1. 模式定义(关键)

  • schema-use-primitives-correctly
    - Use correct primitive schemas for each type
  • schema-use-unknown-not-any
    - Use z.unknown() instead of z.any() for type safety
  • schema-avoid-optional-abuse
    - Avoid overusing optional fields
  • schema-string-validations
    - Apply string validations at schema definition
  • schema-use-enums
    - Use enums for fixed string values
  • schema-coercion-for-form-data
    - Use coercion for form and query data
  • schema-use-primitives-correctly
    - 为每种类型使用正确的原始模式
  • schema-use-unknown-not-any
    - 为保证类型安全,使用z.unknown()而非z.any()
  • schema-avoid-optional-abuse
    - 避免过度使用可选字段
  • schema-string-validations
    - 在模式定义阶段应用字符串验证
  • schema-use-enums
    - 为固定字符串值使用枚举
  • schema-coercion-for-form-data
    - 为表单和查询数据使用强制转换

2. Parsing & Validation (CRITICAL)

2. 解析与验证(关键)

  • parse-use-safeparse
    - Use safeParse() for user input
  • parse-async-for-async-refinements
    - Use parseAsync for async refinements
  • parse-handle-all-issues
    - Handle all validation issues not just first
  • parse-validate-early
    - Validate at system boundaries
  • parse-avoid-double-validation
    - Avoid validating same data twice
  • parse-never-trust-json
    - Never trust JSON.parse output
  • parse-use-safeparse
    - 对用户输入使用safeParse()
  • parse-async-for-async-refinements
    - 对异步细化使用parseAsync
  • parse-handle-all-issues
    - 处理所有验证问题,而非仅第一个
  • parse-validate-early
    - 在系统边界处进行验证
  • parse-avoid-double-validation
    - 避免重复验证同一数据
  • parse-never-trust-json
    - 永远不要信任JSON.parse的输出

3. Type Inference (HIGH)

3. 类型推断(高)

  • type-use-z-infer
    - Use z.infer instead of manual types
  • type-input-vs-output
    - Distinguish z.input from z.infer for transforms
  • type-export-schemas-and-types
    - Export both schemas and inferred types
  • type-branded-types
    - Use branded types for domain safety
  • type-enable-strict-mode
    - Enable TypeScript strict mode
  • type-use-z-infer
    - 使用z.infer而非手动定义类型
  • type-input-vs-output
    - 区分z.input与z.infer以处理转换
  • type-export-schemas-and-types
    - 同时导出模式和推断出的类型
  • type-branded-types
    - 使用品牌类型保障领域安全
  • type-enable-strict-mode
    - 启用TypeScript严格模式

4. Error Handling (HIGH)

4. 错误处理(高)

  • error-custom-messages
    - Provide custom error messages
  • error-use-flatten
    - Use Zod 4 error formatting helpers
  • error-path-for-nested
    - Use issue.path for nested error location
  • error-i18n
    - Implement internationalized error messages
  • error-avoid-throwing-in-refine
    - Return false instead of throwing in refine
  • error-custom-messages
    - 提供自定义错误信息
  • error-use-flatten
    - 使用Zod 4错误格式化工具
  • error-path-for-nested
    - 使用issue.path定位嵌套错误
  • error-i18n
    - 实现多语言错误信息
  • error-avoid-throwing-in-refine
    - 在refine中返回false而非抛出异常

5. Object Schemas (MEDIUM-HIGH)

5. 对象模式(中高)

  • object-strict-vs-strip
    - Choose an explicit unknown-key policy
  • object-partial-for-updates
    - Use partial() for update schemas
  • object-pick-omit
    - Use pick() and omit() for schema variants
  • object-extend-for-composition
    - Use extend() for adding fields
  • object-optional-vs-nullable
    - Distinguish optional() from nullable()
  • object-discriminated-unions
    - Use discriminated unions for type narrowing
  • object-strict-vs-strip
    - 选择明确的未知键处理策略
  • object-partial-for-updates
    - 对更新模式使用partial()
  • object-pick-omit
    - 对模式变体使用pick()和omit()
  • object-extend-for-composition
    - 使用extend()添加字段
  • object-optional-vs-nullable
    - 区分optional()与nullable()
  • object-discriminated-unions
    - 使用可区分联合进行类型收窄

6. Schema Composition (MEDIUM)

6. 模式组合(中)

  • compose-shared-schemas
    - Extract shared schemas into reusable modules
  • compose-intersection
    - Use intersection() for type combinations
  • compose-lazy-recursive
    - Use z.lazy() for recursive schemas
  • compose-preprocess
    - Use preprocess() for data normalization
  • compose-pipe
    - Use pipe() for multi-stage validation
  • compose-shared-schemas
    - 将共享模式提取到可复用模块中
  • compose-intersection
    - 使用intersection()组合类型
  • compose-lazy-recursive
    - 使用z.lazy()定义递归模式
  • compose-preprocess
    - 使用preprocess()进行数据标准化
  • compose-pipe
    - 使用pipe()进行多阶段验证

7. Refinements & Transforms (MEDIUM)

7. 细化与转换(中)

  • refine-vs-superrefine
    - Choose refine() vs superRefine() correctly
  • refine-transform-coerce
    - Distinguish transform() from refine() and coerce()
  • refine-add-path
    - Add path to refinement errors
  • refine-defaults
    - Use default() for optional fields with defaults
  • refine-catch
    - Use catch() for fault-tolerant parsing
  • refine-vs-superrefine
    - 正确选择refine()与superRefine()
  • refine-transform-coerce
    - 区分transform()、refine()与coerce()
  • refine-add-path
    - 为细化错误添加路径
  • refine-defaults
    - 为带默认值的可选字段使用default()
  • refine-catch
    - 使用catch()实现容错解析

8. Performance & Bundle (LOW-MEDIUM)

8. 性能与包体积(中低)

  • perf-cache-schemas
    - Cache schema instances
  • perf-zod-mini
    - Use Zod Mini for bundle-sensitive applications
  • perf-avoid-dynamic-creation
    - Avoid dynamic schema creation in hot paths
  • perf-lazy-loading
    - Lazy load large schemas
  • perf-arrays
    - Optimize large array validation
  • perf-cache-schemas
    - 缓存模式实例
  • perf-zod-mini
    - 对包体积敏感的应用使用Zod Mini
  • perf-avoid-dynamic-creation
    - 避免在热点路径中动态创建模式
  • perf-lazy-loading
    - 懒加载大型模式
  • perf-arrays
    - 优化大型数组验证

How to Use

使用方法

Read individual reference files for detailed explanations and code examples:
  • Section definitions - Category structure and impact levels
  • Individual rules:
    references/{prefix}-{slug}.md
阅读单独的参考文件获取详细说明与代码示例:
  • 章节定义 - 类别结构与影响级别
  • 单个规则:
    references/{prefix}-{slug}.md

Full Compiled Document

完整编译文档

For the complete guide with all rules expanded:
AGENTS.md
包含所有规则扩展说明的完整指南:
AGENTS.md

Related Skills

相关技能

  • For React Hook Form integration, see
    react-hook-form
    skill
  • React Hook Form集成相关内容,请查看
    react-hook-form
    技能

Sources

资料来源