Skip to main content

Overview

One of Zod’s most powerful features is automatic type inference. You define validation logic once, and TypeScript types are automatically generated.

Basic Type Inference with z.infer

Use z.infer<typeof schema> to extract the TypeScript type:
z.infer is actually an alias for z.output. They are identical and interchangeable.

Primitive Types

Complex Types

Arrays

Objects

Unions

Enums

Optional and Nullable Types

z.input vs z.output

When schemas include transformations, the input type (before transformation) differs from the output type (after transformation).

Understanding Input and Output

From packages/zod/src/v4/classic/tests/transform.test.ts:170-174:

When They Differ

Practical Example: Form Coercion

Type Narrowing with Refinements

Refinements can narrow types using type predicates:
From packages/zod/src/v4/classic/tests/refine.test.ts:423-424:

Recursive Types

Zod supports recursive type inference:
From packages/zod/src/v4/classic/tests/recursive-types.test.ts:28-31:

Utility Type Helpers

TypeOf (Alternative to infer)

Extract from Objects

Common Patterns

Sharing Types Between Schema and Interface

API Request/Response Types

Generic Type Utilities

Edge Cases and Special Types

Literal Types

Template Literals

Never Type

Unknown and Any

Best Practices

  1. Define schema once, infer types - Don’t duplicate type definitions
  2. Use z.infer for most cases - It’s an alias for z.output
  3. Use z.input for transformations - When input differs from output
  4. Name types same as schema - Makes code more readable
  5. Export both schema and type - Useful for consumers

TypeScript Integration

Const Assertions

Branded Types

Performance Considerations

Type inference happens at compile time and has zero runtime cost. However, complex recursive types can slow down TypeScript compilation.

Next Steps

  • Learn about Transformations to modify data during parsing
  • Explore Refinements for custom validation with type narrowing
  • Master Schemas to understand all available schema types