TypeScript
/Advanced
Zod & Runtime Validation
Definition
Zod is a TypeScript-first schema declaration and validation library. It solves the critical flaw of TypeScript: TS types disappear at runtime. Zod validates data at runtime AND automatically generates TS types for you.
Explain Like I'm New
TypeScript is an imaginary security guard. It promises your code is safe, but disappears the second the app compiles. If a hacker sends bad JSON to your API, the TS guard isn't there to stop it. Zod is a real, physical security guard. It checks the data while the app is actually running, and rejects it if it doesn't match the rules.
Real World Example
Validating user input from a form or validating the response payload from a 3rd party API before letting it touch your application logic.
Common Use Cases
- •Form validation (React Hook Form)
- •API payload validation in Node.js
- •Environment variable checking
Interactive Example
import { z } from 'zod'; // 1. Create the Zod Schema (The Runtime Guard) const UserSchema = z.object({ username: z.string().min(3, "Must be at least 3 chars"), age: z.number().positive(), email: z.string().email().optional() }); // 2. EXTRACT THE TS TYPE (The magic trick! No duplicate typing needed) type User = z.infer<typeof UserSchema>; // 3. Validate runtime data (e.g., from an API or Form) const incomingApiData = { username: "Al", age: -5 }; // safeParse protects the app from crashing const result = UserSchema.safeParse(incomingApiData); if (!result.success) { console.error("Validation failed!", result.error.issues); } else { // Inside here, TS knows result.data perfectly matches the 'User' type! console.log("Valid user:", result.data.username); }
Interview Questions
basic
- What is the main limitation of TypeScript that Zod solves?
intermediate
- How do you extract a TypeScript type from a Zod schema?
advanced
- What does `schema.parse()` do vs `schema.safeParse()`?