snippettypescriptzodModeratepending
Zod schema validation — runtime type checking in TypeScript
Viewed 0 times
zodschemavalidationparsesafeParseinferruntime types
nodejsbrowser
Problem
TypeScript types are erased at runtime. Need to validate external data (API responses, form inputs, env vars) matches expected shape at runtime, not just at compile time.
Solution
Use Zod for declarative schema validation that infers TypeScript types automatically.
Code Snippets
Zod schema with type inference
import { z } from 'zod';
const UserSchema = z.object({
id: z.string().uuid(),
email: z.string().email(),
age: z.number().int().min(0).max(150),
role: z.enum(['admin', 'user', 'guest']),
metadata: z.record(z.unknown()).optional(),
});
type User = z.infer<typeof UserSchema>;
// User type is automatically inferred
// Throws on invalid data
const user = UserSchema.parse(apiResponse);
// Returns { success, data, error } without throwing
const result = UserSchema.safeParse(apiResponse);
if (result.success) {
console.log(result.data.email);
} else {
console.error(result.error.flatten());
}Revisions (0)
No revisions yet.