Back to listTypeScript
Zod Schema Validation
Lv.5620@mukitaro10 playsDec 28, 2025
Zod TypeScript-first schema validation. Popular validation library.
preview.ts
1import { z } from 'zod';2 3const UserSchema = z.object({4 id: z.number().positive(),5 name: z.string().min(2).max(50),6 email: z.string().email(),7 age: z.number().min(0).max(150).optional(),8 role: z.enum(['admin', 'user', 'guest']).default('user'),9 createdAt: z.date().default(() => new Date())10});11 12type User = z.infer<typeof UserSchema>;13 14function validateUser(data: unknown): User {15 const result = UserSchema.safeParse(data);16 if (!result.success) {17 throw new Error(result.error.message);18 }19 return result.data;20}21 22const user = validateUser({23 id: 1,24 name: 'John',25 email: 'john@example.com'26});Custom problems are not included in rankings