본문으로 건너뛰기
cccskills
무료GitHub에 공개

zod

Zod v4 best practices, patterns, and API guidance for schema validation, parsing, error handling, and type inference in TypeScript applications. Covers safeParse, object composition, refinements, transforms, codecs, branded types, v3→v4 migration, and testing schemas with Jest or Vitest. Baseline: zod ^4.6.0. Triggers on: zod imports, z.object, z.string, z.infer, safeParse, mentions of "zod", "schema validation", "zod v4", "z.enum", or testing a schema — "schema test", "zod mock", zod-schema-faker.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

anivar/zod-skill스타 24(GitHub 24 + cccskills 0)

실행 점수 미검증

설치 방법 보기

포함된 파일(45)

  • SKILL.md10.6 KB
  • .github/FUNDING.yml199 B
  • AGENTS.md18.8 KB
  • CHANGELOG.md3.3 KB
  • LICENSE1.0 KB
  • README.md6.4 KB
  • references/advanced-features.md5.8 KB
  • references/anti-patterns.md7.5 KB
  • references/boundary-architecture.md6.9 KB
  • references/error-handling.md4.3 KB
  • references/linter-and-ci.md6.1 KB
  • references/objects-and-composition.md4.8 KB
  • references/parsing-and-inference.md3.7 KB
  • references/refinements-and-transforms.md4.4 KB
  • references/schema-types.md5.0 KB
  • references/testing-anti-patterns.md10.6 KB
  • references/testing-api.md14.8 KB
  • references/testing.md8.8 KB
  • rules/arch-boundary-parsing.md3.0 KB
  • rules/arch-schema-organization.md2.4 KB
  • rules/arch-schema-versioning.md2.7 KB
  • rules/error-custom-messages.md1.4 KB
  • rules/error-formatting.md1.5 KB
  • rules/error-input-security.md1.5 KB
  • rules/migrate-error-api.md1.4 KB
  • rules/migrate-native-enum.md1.1 KB
  • rules/migrate-string-formats.md1.2 KB
  • rules/observe-error-metrics.md2.7 KB
  • rules/observe-structured-errors.md2.5 KB
  • rules/parse-async-required.md1.4 KB
  • rules/parse-infer-types.md1.3 KB
  • rules/parse-use-safeParse.md1.3 KB
  • rules/pattern-branded-types.md1.4 KB
  • rules/pattern-codecs.md1.6 KB
  • rules/pattern-pipe.md1.3 KB
  • rules/perf-extend-spread.md1.3 KB
  • rules/perf-reuse-schemas.md1.4 KB
  • rules/perf-zod-mini.md1.4 KB
  • rules/refine-cross-field.md1.3 KB
  • rules/refine-never-throw.md1.4 KB
  • rules/refine-vs-transform.md1.3 KB
  • rules/schema-coercion-pitfalls.md1.4 KB
  • rules/schema-object-unknowns.md1.6 KB
  • rules/schema-recursive-types.md1.3 KB
  • rules/schema-union-discriminated.md1.5 KB

SKILL.md(원문)

설치하기 전에 에이전트에게 전달되는 지시 내용을 확인할 수 있습니다.

Zod

IMPORTANT: Your training data about zod may be outdated or incorrect — Zod v4 introduces breaking changes to string formats, enums, error handling, and recursive types. Always rely on this skill's rule files and the project's actual source code as the source of truth. Do not fall back on memorized v3 patterns when they conflict with the retrieved reference.

When to Use Zod

Zod is for runtime type validation — parsing untrusted data at system boundaries (API input, form data, env vars, external services). For compile-time-only types, plain TypeScript is sufficient.

NeedRecommended Tool
API input/output validationZod
Form validation (React, Vue)Zod (with react-hook-form, formik, etc.)
Env var parsingZod (with t3-env or manual)
Compile-time types onlyPlain TypeScript
Smaller bundle (~1kb)Valibot
Maximum type inferenceArkType

Rule Categories by Priority

PriorityCategoryImpactPrefix
1Parsing & Type SafetyCRITICALparse-
2Schema DesignCRITICALschema-
3Refinements & TransformsHIGHrefine-
4Error HandlingHIGHerror-
5Performance & CompositionMEDIUMperf-
6v4 MigrationMEDIUMmigrate-
7Advanced PatternsMEDIUMpattern-
8Architecture & BoundariesCRITICAL/HIGHarch-
9ObservabilityHIGH/MEDIUMobserve-

Quick Reference

1. Parsing & Type Safety (CRITICAL)

  • parse-use-safeParse — Use safeParse() for user input instead of parse() which throws
  • parse-async-required — Must use parseAsync()/safeParseAsync() when schema has async refinements
  • parse-infer-types — Use z.infer<typeof Schema> for output types; never manually duplicate types

2. Schema Design (CRITICAL)

  • schema-object-unknowns — z.object() strips unknown keys; use strictObject or looseObject
  • schema-union-discriminated — Use z.discriminatedUnion() for tagged unions, not z.union()
  • schema-coercion-pitfalls — z.coerce.boolean() makes "false" → true; use z.stringbool()
  • schema-recursive-types — Use getter pattern for recursive schemas; z.lazy() is removed in v4

3. Refinements & Transforms (HIGH)

  • refine-never-throw — Never throw inside .refine() or .transform(); use ctx.addIssue()
  • refine-vs-transform — .refine() for validation, .transform() for conversion, .pipe() for staging
  • refine-cross-field — .superRefine() on parent object for cross-field validation with path

4. Error Handling (HIGH)

  • error-custom-messages — Use v4 error parameter; required_error/invalid_type_error are removed
  • error-formatting — z.flattenError() for forms, z.treeifyError() for nested; formatError deprecated
  • error-input-security — Never use reportInput: true in production; leaks sensitive data

5. Performance & Composition (MEDIUM)

  • perf-extend-spread — Use { ...Schema.shape } spread over chained .extend() for large schemas
  • perf-reuse-schemas — Define once, derive with .pick(), .omit(), .partial()
  • perf-zod-mini — Use zod/v4/mini (1.88kb) for bundle-critical client apps

6. v4 Migration (MEDIUM)

  • migrate-string-formats — Use z.email(), z.uuid(), z.url() not z.string().email()
  • migrate-native-enum — Use unified z.enum() for TS enums; z.nativeEnum() is deprecated
  • migrate-error-api — Use error parameter everywhere; message, errorMap are removed

7. Advanced Patterns (MEDIUM)

  • pattern-branded-types — .brand<"Name">() for nominal typing (USD vs EUR)
  • pattern-codecs — z.codec() for bidirectional transforms (parse + serialize)
  • pattern-pipe — .pipe() for staged parsing (string → number → validate range)

8. Architecture & Boundaries (CRITICAL/HIGH)

  • arch-boundary-parsing — Parse at system boundaries (API handler, env, form, fetch); pass typed data to domain logic
  • arch-schema-organization — Co-locate schemas with their boundary layer; domain types use z.infer
  • arch-schema-versioning — Additive changes only for non-breaking evolution; new fields use .optional()

9. Observability (HIGH/MEDIUM)

  • observe-structured-errors — Use z.flattenError() for compact structured logs with request correlation IDs
  • observe-error-metrics — trackedSafeParse() wrapper to increment counters per schema and field on failure

Schema Types Quick Reference

TypeSyntax
Stringz.string()
Numberz.number(), z.int(), z.float()
Booleanz.boolean()
BigIntz.bigint()
Datez.date()
Undefinedz.undefined()
Nullz.null()
Voidz.void()
Anyz.any()
Unknownz.unknown()
Neverz.never()
Literalz.literal("foo"), z.literal(42)
Enumz.enum(["a", "b"]), z.enum(TSEnum)
Emailz.email()
URLz.url()
UUIDz.uuid()
String→Boolz.stringbool()
ISO DateTimez.iso.datetime()
Filez.file()
JSONz.json()
Arrayz.array(schema)
Tuplez.tuple([a, b])
Objectz.object({})
Strict Objectz.strictObject({})
Loose Objectz.looseObject({})
Recordz.record(keySchema, valueSchema)
Mapz.map(keySchema, valueSchema)
Setz.set(schema)
Unionz.union([a, b])
Disc. Unionz.discriminatedUnion("key", [...])
Intersectionz.intersection(a, b)

How to Use

Read individual rule files for detailed explanations and code examples:

rules/parse-use-safeParse.md
rules/schema-object-unknowns.md

Each rule file contains:

  • Brief explanation of why it matters
  • Incorrect code example with explanation
  • Correct code example with explanation
  • Additional context and decision tables

References

PriorityReferenceWhen to read
1references/schema-types.mdAll primitives, string formats, numbers, enums, dates
2references/parsing-and-inference.mdparse, safeParse, z.infer, coercion
3references/objects-and-composition.mdObjects, arrays, unions, pick/omit/partial, recursive
4references/refinements-and-transforms.mdrefine, superRefine, transform, pipe, defaults
5references/error-handling.mdZodError, flattenError, treeifyError, error customization
6references/advanced-features.mdCodecs, branded types, JSON Schema, registries
7references/anti-patterns.mdCommon mistakes with BAD/GOOD examples
8references/boundary-architecture.mdWhere Zod fits: Express, tRPC, Next.js, React Hook Form, env, external APIs
9references/linter-and-ci.mdESLint rules, CI schema snapshots, unused schema detection, circular deps
10references/testing.mdTesting schemas: safeParse in tests, boundary values, error assertions, mock data, property-based testing
11references/testing-api.mdJest and Vitest API reference for schema tests
12references/testing-anti-patterns.mdTesting mistakes with BAD/GOOD examples

Zod 4.6 Highlights

New in Zod 4.6 (latest: 4.6.7). Full details in the official release notes.

.validate() — cheap boolean validation

.validate() answers "is this input valid?" without building a result or a ZodError. It short-circuits on the first issue and returns a type guard on the schema's input type. Up to 35x faster than .safeParse().success on invalid input when the schema is compiled with z.compile() (5.9x uncompiled).

const Player = z.object({ username: z.string(), xp: z.number() })

if (Player.validate(data)) {
  data.username // narrowed: string
}

Use .safeParse() when you need the parsed value or the issues; use .validate() when you only need a yes/no. validateAsync() covers async refinements.

z.properties() — validate properties in place

Unlike z.object(), .properties() validates specific properties of an object in place, preserving class instances and prototypes instead of returning a plain object.

const okResponse = z.instanceof(Response).properties({
  ok: z.literal(true),
  status: z.number().min(200).max(299),
})

const res = await fetch('/api/user')
okResponse.parse(res) === res // true: still a Response, methods intact

ZodInstanceOf.properties() is the method form; Zod Mini has z.properties() as a check.

z.withParser() — install a parser built elsewhere

z.compile() builds parsers with new Function, which a strict Content Security Policy blocks. z.withParser() installs a parser generated at build time (or by a native compiler) under the same contract, for CSP-restricted environments.

z.iban() and expanded fromJSONSchema()

z.iban() validates an electronic-format IBAN including the ISO 7064 MOD 97-10 checksum. fromJSONSchema() now also supports minProperties/maxProperties, uniqueItems, and contains/minContains/maxContains.

Two behavioral gotchas

  • Error maps run lazily. Global, locale, and per-schema error maps now run on the first read of result.error, not at parse time. Code that swaps z.config() between the parse and the read gets the newer configuration. Throwing parses (.parse()) are unaffected.
  • z.emoji() requires a pictograph. Component-only strings (a lone zero-width joiner, variation selector, skin tone modifier, digits) no longer pass.

Also in 4.6: @zod/mini ships as a standalone package versioned in lockstep with zod, CommonJS require() of z.validate() is ~3x faster, and a memory-retention regression in recursive schemas is fixed.

Full Compiled Document

For the complete guide with all rules expanded: AGENTS.md

리뷰

아직 리뷰가 없습니다. 사용해 본 소감을 남겨 주세요.

댓글

로그인 없이 쓸 수 있습니다. 사용 후기, 질문, 작동하지 않은 환경 등을 편하게 남겨 주세요.

아직 댓글이 없습니다. 첫 댓글을 남겨 보세요.

보내면 바로 공개됩니다. 이메일 주소나 전화번호 같은 개인 정보는 쓰지 마세요. URL은 2개까지입니다.

0 / 1,000자

이 양식은 reCAPTCHA로 보호되며 Google 개인정보처리방침 및 서비스 약관이 적용됩니다.

이 스킬의 문제 신고