Type safety is one of the most powerful features of TypeScript, but it only works at compile time. Runtime validation is still necessary to ensure data integrity. In this article, we'll explore how to combine TypeScript with Zod to create truly type-safe APIs.
Why Runtime Validation Matters
TypeScript provides compile-time type checking, but once your code is running, you can't trust that the data coming from external sources (APIs, user input, databases) matches your types. Runtime validation with Zod ensures data integrity and provides better error messages.
1import { z } from 'zod'2
3// Define schema4const UserSchema = z.object({5 id: z.string().uuid(),6 email: z.string().email(),7 name: z.string().min(1),8 age: z.number().int().positive(),9})10
11// Infer TypeScript type from schema12type User = z.infer<typeof UserSchema>13
14// Validate at runtime15function createUser(data: unknown): User {16 return UserSchema.parse(data) // Throws if invalid17}Pro Tip