รู้จักสคีมา Zod
สำรวจ Zod ซึ่งเป็นไลบรารีประกาศและตรวจสอบสคีมาที่ออกแบบมาสำหรับ TypeScript รวมถึงชนิดข้อมูลพื้นฐานของไลบรารีนี้
รู้จักสคีมา Zod เป็นบทเรียน tRPC End-to-End Type Safe APIs ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน 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...catchfor error handling. .optional()allowsundefinedvalues.z.literal()enforces exact fixed values.
These skills are foundational for building robust, type-safe applications!
คำถามที่พบบ่อย
บทเรียน “รู้จักสคีมา Zod” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “รู้จักสคีมา Zod” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส 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 ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน tRPC End-to-End Type Safe APIs หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน tRPC End-to-End Type Safe APIs บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน
บทเรียน “รู้จักสคีมา Zod” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน tRPC End-to-End Type Safe APIs นี้ได้ไหม
ได้ บทเรียน tRPC End-to-End Type Safe APIs ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- รู้จักสคีมา Zod
- การกำหนดสคีมา Zod ที่ซับซ้อน
- การผสานรวม Zod ในกระบวนงาน tRPC
- การแปลงและปรับแต่งข้อมูล Zod