0Pricing
tRPC End-to-End Type Safe APIs · 课时

Zod 模式简介

探索 Zod——一个以 TypeScript 为先的模式声明与验证库——及其基本类型。

Zod 模式简介 是 CoddyKit 上的免费 tRPC End-to-End Type Safe APIs 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 tRPC End-to-End Type Safe APIs 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 tRPC End-to-End Type Safe APIs 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

What is Zod?

Welcome to Zod! It's a powerful, TypeScript-first validation library. Think of it as a guardian for your data.

Zod helps ensure that the data entering your application (from APIs, forms, etc.) matches the types you expect, even at runtime.

Why Use Zod? Type Safety!

TypeScript provides type safety during development, but what about data received from a server or user input? That data doesn't have TypeScript types.

Zod bridges this gap! It allows you to define a schema, validate runtime data against it, and automatically infer a TypeScript type from that schema. This gives you end-to-end type safety.

Zod's Basic Building Blocks

Zod schemas are created using the z object. Let's look at the most fundamental types: strings, numbers, and booleans.

  • z.string(): For text values.
  • z.number(): For numeric values.
  • z.boolean(): For true/false values.

These are your starting points for defining data shapes.

Declaring a String Schema

A string schema is simple to declare. You then use the .parse() method to validate data against it. If the data doesn't match, Zod throws an error.

Try running this example to see a valid string being parsed:

import { z } from 'zod';

function runExample() {
  const usernameSchema = z.string();

  const validUsername = "CoddyUser";
  const parsedUsername = usernameSchema.parse(validUsername);
  console.log(`Parsed: ${parsedUsername}`);
}

runExample();

Handling String Validation Errors

What happens if you try to parse data that isn't a string? Zod throws a ZodError. It's good practice to wrap .parse() calls in a try...catch block.

Run this code to see Zod catch an invalid type:

import { z } from 'zod';

function runExample() {
  const usernameSchema = z.string();

  try {
    const invalidUsername = 123; // Not a string!
    usernameSchema.parse(invalidUsername);
  } catch (error: any) {
    console.log(`Error: ${error.message.split('\n')[0]}`);
  }
}

runExample();

Number & Boolean Schemas

Number and boolean schemas work similarly. They ensure the data is of the correct primitive type. This prevents unexpected errors later in your application.

Let's see how to define and use them:

import { z } from 'zod';

function runExample() {
  const ageSchema = z.number();
  const isActiveSchema = z.boolean();

  const validAge = ageSchema.parse(30);
  console.log(`Age: ${validAge}`);

  const validStatus = isActiveSchema.parse(true);
  console.log(`Active: ${validStatus}`);

  try {
    ageSchema.parse("twenty"); // Invalid!
  } catch (error: any) {
    console.log(`Error (Age): ${error.message.split('\n')[0]}`);
  }
}

runExample();

Making Fields Optional

Sometimes a piece of data might not always be present. Zod provides the .optional() method for this. It makes a schema accept undefined in addition to its base type.

Note that .optional() allows undefined, but not null by default.

import { z } from 'zod';

function runExample() {
  const taglineSchema = z.string().optional();

  const withTagline = taglineSchema.parse("Hello World!");
  console.log(`With tagline: ${withTagline}`);

  const withoutTagline = taglineSchema.parse(undefined);
  console.log(`Without tagline: ${withoutTagline}`);

  try {
    taglineSchema.parse(null); // Optional doesn't allow null!
  } catch (error: any) {
    console.log(`Error (null): ${error.message.split('\n')[0]}`);
  }
}

runExample();

Exact Values with Literals

What if you need a field to have a very specific, fixed value? Zod's .literal() method is perfect for this. It ensures the parsed value is exactly what you define.

This is useful for enum-like fields where values are known beforehand.

import { z } from 'zod';

function runExample() {
  const statusSchema = z.literal("pending");

  const validStatus = statusSchema.parse("pending");
  console.log(`Valid status: ${validStatus}`);

  try {
    statusSchema.parse("completed"); // Not 'pending'!
  } catch (error: any) {
    console.log(`Error (status): ${error.message.split('\n')[0]}`);
  }
}

runExample();

Building Blocks for Complex Data

You've now seen the basic types and modifiers in Zod. While simple on their own, these are the fundamental building blocks.

In upcoming lessons, you'll learn how to combine these basic schemas to define much more complex data structures, like objects and arrays, ensuring robust validation for your entire application.

Check Your Zod Basics!

Which Zod schema correctly validates a variable that must be the string "admin" or optionally a number?

Zod Basics Recap

Great job! You've taken your first steps into Zod, understanding its core purpose and basic types.

  • Zod provides runtime validation for TypeScript data.
  • z.string(), z.number(), z.boolean() define basic types.
  • .parse() validates data and infers types.
  • Use try...catch for error handling.
  • .optional() allows undefined values.
  • z.literal() enforces exact fixed values.

These skills are foundational for building robust, type-safe applications!

常见问题解答

「Zod 模式简介」课时是免费的吗?

是的 — 「Zod 模式简介」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 tRPC End-to-End Type Safe APIs 课程的其余内容,请升级到 CoddyKit PRO。 tRPC End-to-End Type Safe APIs 课程共包含 4 节课。

「Zod 模式简介」这节课中我会学到什么?

探索 Zod——一个以 TypeScript 为先的模式声明与验证库——及其基本类型。 你通过在浏览器中直接运行的动手代码来练习 tRPC End-to-End Type Safe APIs,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 tRPC End-to-End Type Safe APIs 需要有经验吗?

无需任何先前经验。CoddyKit 上的 tRPC End-to-End Type Safe APIs 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。

「Zod 模式简介」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 tRPC End-to-End Type Safe APIs 课中编写并运行代码吗?

能。每节 tRPC End-to-End Type Safe APIs 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. Zod 模式简介
  2. 定义复杂的 Zod 模式
  3. 在 tRPC 过程中集成 Zod
  4. 转换与细化 Zod 数据
← 返回 tRPC End-to-End Type Safe APIs