zod

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Zod Best Practices

Zod最佳实践

Comprehensive schema validation guide for Zod in TypeScript applications. Contains 43 rules across 8 categories, prioritized by impact to guide automated refactoring and code generation.
TypeScript应用中Zod的全面Schema验证指南。包含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 Schema
  • 在parse()和safeParse()之间做选择
  • 使用z.infer实现类型推断
  • 处理验证错误以提供用户反馈
  • 组合复杂的对象Schema
  • 使用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-
优先级类别影响程度前缀
1Schema定义关键
schema-
2解析与验证关键
parse-
3类型推断
type-
4错误处理
error-
5对象Schema中高
object-
6Schema组合
compose-
7细化与转换
refine-
8性能与包体积中低
perf-

Quick Reference

快速参考

1. Schema Definition (CRITICAL)

1. Schema定义(关键)

  • 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
  • schema-use-unknown-not-any
    - 为了类型安全,使用z.unknown()而非z.any()
  • schema-avoid-optional-abuse
    - 避免过度使用可选字段
  • schema-string-validations
    - 在Schema定义阶段应用字符串验证
  • 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
    - 同时导出Schema和推断出的类型
  • type-branded-types
    - 使用品牌类型保证领域安全
  • type-enable-strict-mode
    - 启用TypeScript严格模式

4. Error Handling (HIGH)

4. 错误处理(高)

  • error-custom-messages
    - Provide custom error messages
  • error-use-flatten
    - Use flatten() for form error display
  • 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
    - 使用flatten()显示表单错误
  • error-path-for-nested
    - 使用issue.path定位嵌套错误
  • error-i18n
    - 实现多语言错误消息
  • error-avoid-throwing-in-refine
    - 在refine中返回false而非抛出异常

5. Object Schemas (MEDIUM-HIGH)

5. 对象Schema(中高)

  • object-strict-vs-strip
    - Choose strict() vs strip() for unknown keys
  • 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
    - 为未知键选择strict()或strip()
  • object-partial-for-updates
    - 对更新Schema使用partial()
  • object-pick-omit
    - 使用pick()和omit()创建Schema变体
  • object-extend-for-composition
    - 使用extend()添加字段
  • object-optional-vs-nullable
    - 区分optional()和nullable()
  • object-discriminated-unions
    - 使用区分联合进行类型收窄

6. Schema Composition (MEDIUM)

6. Schema组合(中)

  • 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
    - 将共享Schema提取到可复用模块中
  • compose-intersection
    - 使用intersection()组合类型
  • compose-lazy-recursive
    - 使用z.lazy()定义递归Schema
  • 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
    - 缓存Schema实例
  • perf-zod-mini
    - 对包体积敏感的应用使用Zod Mini
  • perf-avoid-dynamic-creation
    - 避免在热点路径中动态创建Schema
  • perf-lazy-loading
    - 懒加载大型Schema
  • perf-arrays
    - 优化大型数组验证

How to Use

使用方法

Read individual reference files for detailed explanations and code examples:
  • Section definitions - Category structure and impact levels
  • Rule template - Template for adding new rules
  • 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
  • For API client generation, see
    orval
    skill
  • 如需React Hook Form集成,请查看
    react-hook-form
    技能
  • 如需API客户端生成,请查看
    orval
    技能

Sources

参考来源