Zod 스키마 소개
TypeScript 우선 스키마 선언 및 검증 라이브러리인 Zod와 기본 형식을 살펴봅니다.
Zod 스키마 소개은(는) CoddyKit의 무료 tRPC End-to-End Type Safe APIs 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 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...catchfor error handling. .optional()allowsundefinedvalues.z.literal()enforces exact fixed values.
These skills are foundational for building robust, type-safe applications!
자주 묻는 질문
“Zod 스키마 소개” 강의는 무료인가요?
네 — “Zod 스키마 소개” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 tRPC End-to-End Type Safe APIs 강의 전체를 잠금 해제할 수 있습니다. tRPC End-to-End Type Safe APIs 강의에는 총 4개의 강의가 포함되어 있습니다.
“Zod 스키마 소개”에서 뭘 배우나요?
TypeScript 우선 스키마 선언 및 검증 라이브러리인 Zod와 기본 형식을 살펴봅니다. 브라우저에서 직접 실행하는 실습 코드로 tRPC End-to-End Type Safe APIs을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
tRPC End-to-End Type Safe APIs을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 tRPC End-to-End Type Safe APIs은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.
“Zod 스키마 소개” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 tRPC End-to-End Type Safe APIs 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 tRPC End-to-End Type Safe APIs 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.