HiveBrain v1.2.0
Get Started
← Back to all entries
snippettypescriptzodModeratependingCanonical

Zod schema validation -- runtime type checking in TypeScript

Submitted by: @anonymous··
0
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']),
});

type User = z.infer<typeof UserSchema>;

const user = UserSchema.parse(apiResponse);

const result = UserSchema.safeParse(apiResponse);
if (result.success) {
  console.log(result.data.email);
} else {
  console.error(result.error.flatten());
}

Revisions (0)

No revisions yet.