zod
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseZod 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
按优先级划分的规则类别
| Priority | Category | Impact | Prefix |
|---|---|---|---|
| 1 | Schema Definition | CRITICAL | |
| 2 | Parsing & Validation | CRITICAL | |
| 3 | Type Inference | HIGH | |
| 4 | Error Handling | HIGH | |
| 5 | Object Schemas | MEDIUM-HIGH | |
| 6 | Schema Composition | MEDIUM | |
| 7 | Refinements & Transforms | MEDIUM | |
| 8 | Performance & Bundle | LOW-MEDIUM | |
| 优先级 | 类别 | 影响程度 | 前缀 |
|---|---|---|---|
| 1 | Schema定义 | 关键 | |
| 2 | 解析与验证 | 关键 | |
| 3 | 类型推断 | 高 | |
| 4 | 错误处理 | 高 | |
| 5 | 对象Schema | 中高 | |
| 6 | Schema组合 | 中 | |
| 7 | 细化与转换 | 中 | |
| 8 | 性能与包体积 | 中低 | |
Quick Reference
快速参考
1. Schema Definition (CRITICAL)
1. Schema定义(关键)
- - Use correct primitive schemas for each type
schema-use-primitives-correctly - - Use z.unknown() instead of z.any() for type safety
schema-use-unknown-not-any - - Avoid overusing optional fields
schema-avoid-optional-abuse - - Apply string validations at schema definition
schema-string-validations - - Use enums for fixed string values
schema-use-enums - - Use coercion for form and query data
schema-coercion-for-form-data
- - 为每种类型使用正确的基础Schema
schema-use-primitives-correctly - - 为了类型安全,使用z.unknown()而非z.any()
schema-use-unknown-not-any - - 避免过度使用可选字段
schema-avoid-optional-abuse - - 在Schema定义阶段应用字符串验证
schema-string-validations - - 为固定字符串值使用枚举
schema-use-enums - - 为表单和查询数据使用强制转换
schema-coercion-for-form-data
2. Parsing & Validation (CRITICAL)
2. 解析与验证(关键)
- - Use safeParse() for user input
parse-use-safeparse - - Use parseAsync for async refinements
parse-async-for-async-refinements - - Handle all validation issues not just first
parse-handle-all-issues - - Validate at system boundaries
parse-validate-early - - Avoid validating same data twice
parse-avoid-double-validation - - Never trust JSON.parse output
parse-never-trust-json
- - 对用户输入使用safeParse()
parse-use-safeparse - - 对异步细化使用parseAsync
parse-async-for-async-refinements - - 处理所有验证问题,而非仅第一个
parse-handle-all-issues - - 在系统边界处进行验证
parse-validate-early - - 避免重复验证同一数据
parse-avoid-double-validation - - 永远不要信任JSON.parse的输出
parse-never-trust-json
3. Type Inference (HIGH)
3. 类型推断(高)
- - Use z.infer instead of manual types
type-use-z-infer - - Distinguish z.input from z.infer for transforms
type-input-vs-output - - Export both schemas and inferred types
type-export-schemas-and-types - - Use branded types for domain safety
type-branded-types - - Enable TypeScript strict mode
type-enable-strict-mode
- - 使用z.infer而非手动定义类型
type-use-z-infer - - 区分z.input和z.infer以处理转换
type-input-vs-output - - 同时导出Schema和推断出的类型
type-export-schemas-and-types - - 使用品牌类型保证领域安全
type-branded-types - - 启用TypeScript严格模式
type-enable-strict-mode
4. Error Handling (HIGH)
4. 错误处理(高)
- - Provide custom error messages
error-custom-messages - - Use flatten() for form error display
error-use-flatten - - Use issue.path for nested error location
error-path-for-nested - - Implement internationalized error messages
error-i18n - - Return false instead of throwing in refine
error-avoid-throwing-in-refine
- - 提供自定义错误消息
error-custom-messages - - 使用flatten()显示表单错误
error-use-flatten - - 使用issue.path定位嵌套错误
error-path-for-nested - - 实现多语言错误消息
error-i18n - - 在refine中返回false而非抛出异常
error-avoid-throwing-in-refine
5. Object Schemas (MEDIUM-HIGH)
5. 对象Schema(中高)
- - Choose strict() vs strip() for unknown keys
object-strict-vs-strip - - Use partial() for update schemas
object-partial-for-updates - - Use pick() and omit() for schema variants
object-pick-omit - - Use extend() for adding fields
object-extend-for-composition - - Distinguish optional() from nullable()
object-optional-vs-nullable - - Use discriminated unions for type narrowing
object-discriminated-unions
- - 为未知键选择strict()或strip()
object-strict-vs-strip - - 对更新Schema使用partial()
object-partial-for-updates - - 使用pick()和omit()创建Schema变体
object-pick-omit - - 使用extend()添加字段
object-extend-for-composition - - 区分optional()和nullable()
object-optional-vs-nullable - - 使用区分联合进行类型收窄
object-discriminated-unions
6. Schema Composition (MEDIUM)
6. Schema组合(中)
- - Extract shared schemas into reusable modules
compose-shared-schemas - - Use intersection() for type combinations
compose-intersection - - Use z.lazy() for recursive schemas
compose-lazy-recursive - - Use preprocess() for data normalization
compose-preprocess - - Use pipe() for multi-stage validation
compose-pipe
- - 将共享Schema提取到可复用模块中
compose-shared-schemas - - 使用intersection()组合类型
compose-intersection - - 使用z.lazy()定义递归Schema
compose-lazy-recursive - - 使用preprocess()进行数据规范化
compose-preprocess - - 使用pipe()进行多阶段验证
compose-pipe
7. Refinements & Transforms (MEDIUM)
7. 细化与转换(中)
- - Choose refine() vs superRefine() correctly
refine-vs-superrefine - - Distinguish transform() from refine() and coerce()
refine-transform-coerce - - Add path to refinement errors
refine-add-path - - Use default() for optional fields with defaults
refine-defaults - - Use catch() for fault-tolerant parsing
refine-catch
- - 正确选择refine()和superRefine()
refine-vs-superrefine - - 区分transform()、refine()和coerce()
refine-transform-coerce - - 为细化错误添加路径
refine-add-path - - 对带默认值的可选字段使用default()
refine-defaults - - 使用catch()实现容错解析
refine-catch
8. Performance & Bundle (LOW-MEDIUM)
8. 性能与包体积(中低)
- - Cache schema instances
perf-cache-schemas - - Use Zod Mini for bundle-sensitive applications
perf-zod-mini - - Avoid dynamic schema creation in hot paths
perf-avoid-dynamic-creation - - Lazy load large schemas
perf-lazy-loading - - Optimize large array validation
perf-arrays
- - 缓存Schema实例
perf-cache-schemas - - 对包体积敏感的应用使用Zod Mini
perf-zod-mini - - 避免在热点路径中动态创建Schema
perf-avoid-dynamic-creation - - 懒加载大型Schema
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
- 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.mdRelated Skills
相关技能
- For React Hook Form integration, see skill
react-hook-form - For API client generation, see skill
orval
- 如需React Hook Form集成,请查看技能
react-hook-form - 如需API客户端生成,请查看技能
orval