

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 7
click for more info
Not enough gems
Cost: 6 gems
1: The Runtime Problem
incomplete
2: Validation Libraries
incomplete
3: Schemas and Type Inference
incomplete
4: Why Validate?
incomplete
This lesson's interactive features are locked, please to keep using them
Zod schemas can both validate runtime data and generate TypeScript types, giving you a single source of truth for your data structures.
Use your schema's parse() method to validate data. It returns the validated data or throws a ZodError:
import { z } from "zod";
const UserSchema = z.object({
id: z.number(),
name: z.string(),
});
try {
const user = UserSchema.parse(unknownData);
// user is now typed and validated
console.log(user.name); // TypeScript knows this is a string
} catch (error) {
if (error instanceof z.ZodError) {
console.error("Validation failed:", error.errors);
}
}
A safeParse method exists which returns a result type instead of throwing.
Zod can automatically generate TypeScript types from your schemas using z.infer:
type User = z.infer<typeof UserSchema>;
// User is: { id: number; name: string }
This means you define your data structure once in the schema, and get both:
parse()z.inferYou don't need to maintain two definitions with separate TypeScript interfaces and validation logic:
interface User {
id: number;
name: string;
}
function validateUser(data: any): User {
// Manual validation logic...
}
Instead, you can have a single definition that provides both runtime validation and compile-time types:
const UserSchema = z.object({
id: z.number(),
name: z.string(),
});
type User = z.infer<typeof UserSchema>;
Put your Jello issue schema to work in a real API call. You'll update a fetch call to use proper validation.
You might find the Array.isArray() method useful.