DEV Community

Siddharth Gupta
Siddharth Gupta

Posted on

Understanding Optional Parameters: TypeScript Interface vs Zod Schema

Ever encountered a situation where your TypeScript interface works fine with optional parameters, but Zod schema throws an error? Let's break down this interesting difference!

The Problem
Consider this autocomplete component with optional parameters:

Image description

Why This Happens?

-> TypeScript Interface:

  • Follows JavaScript's natural function behavior
  • Optional parameters can be completely omitted
  • More flexible, compile-time only

-> Zod Schema:

  • Enforces runtime validation
  • .args() requires all parameters to be provided, even if undefined
  • Stricter validation for data safety

When to Use What?

-> Use TypeScript Interface when:

  • You want flexible, natural JavaScript function behavior
  • You're doing compile-time type checking only
  • Working with UI components and callbacks

-> Use Zod Schema when:

  • You need runtime validation
  • Working with API payloads or external data
  • Need to enforce strict parameter validation

Top comments (3)

Collapse
 
vidakhoshpey22 profile image
Vida Khoshpey

Keep going ๐Ÿ’ช๐Ÿป let me see it ๐Ÿ˜

Collapse
 
hamster_007 profile image
Siddharth Gupta

thanks

Collapse
 
dotallio profile image
Dotallio

Iโ€™ve definitely hit Zod errors when expecting TS-style omission to โ€œjust work.โ€ Have you found a smooth way to handle truly optional props in Zod without cluttering up all the schemas?