We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Schemas and Type Inference

Zod schemas can both validate runtime data and generate TypeScript types, giving you a single source of truth for your data structures.

Parsing With Schemas

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.

z.infer

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:

  • Runtime validation via parse()
  • Compile-time TypeScript types via z.infer

Single Source of Truth

You 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>;

Assignment

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.