Typescript์—์„œ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋Š” ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ Zod์˜ ๊ธฐ์ดˆ ์‚ฌ์šฉ๋ฒ•

zod.dev

๐Ÿค”Zod ๊ฐ€ ๋ฌด์—‡์ธ๊ฐ€์š”?

Zod is a TypeScript-first schema declaration and validation library.

Zod๋Š” ํƒ€์ž…์Šคํฌ๋ฆฝํŠธ ์šฐ์„  ์Šคํ‚ค๋งˆ ์„ ์–ธ ๋ฐ ๊ฒ€์ฆ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ ์ž…๋‹ˆ๋‹ค.

๐Ÿค”์™œ Zod๋ฅผ ์‚ฌ์šฉํ•˜๋‚˜์š”?

ํƒ€์ž…์Šคํฌ๋ฆฝํŠธ๋Š” ์ปดํŒŒ์ผ ์‹œ์ ์—์„œ ํƒ€์ž…์„ ๊ฒ€์‚ฌํ•ฉ๋‹ˆ๋‹ค. ๋Ÿฐํƒ€์ž„์— ๋™์ ์œผ๋กœ ์ƒ์„ฑ๋˜๋Š” ๊ฐ’๊ณผ ํƒ€์ž…์Šคํฌ๋ฆฝํŠธ์˜ ํƒ€์ž… ๊ฐ„์˜ ๋ถˆ์ผ์น˜๊ฐ€ ๋ฐœ์ƒํ•˜์—ฌ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•  ์ˆ˜ ์žˆ๋Š”๋ฐ์š”, ์ด๋ฅผ ๋ฐฉ์ง€ํ•  ์ˆ˜ ์žˆ๋Š” ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๊ฐ€ ๋ฐ”๋กœ Zod์ž…๋‹ˆ๋‹ค.

์•„๋ž˜์™€ ๊ฐ™์€ ์ƒํ™ฉ์ด ๋Ÿฐํƒ€์ž„์— ๋™์ ์œผ๋กœ ์ƒ์„ฑ๋˜๋Š” ๊ฐ’๊ณผ ํƒ€์ž…์Šคํฌ๋ฆฝํŠธ ํƒ€์ž… ๊ฐ„์˜ ๋ถˆ์ผ์น˜๊ฐ€ ๋ฐœ์ƒํ•˜๋Š” ์ฝ”๋“œ์˜ ์˜ˆ ์ž…๋‹ˆ๋‹ค.

interface User {
  id: number;
  name: string;
}

const Json = '{"id": 1323, "username": "lurgi"}';

try {
  const user: User = JSON.parse(Json);
  console.log(user.id);
  console.log(user.name);
} catch (error) {
  console.error('๋Ÿฐํƒ€์ž„ ์—๋Ÿฌ:', error);
}

/*
์‹คํ–‰ ๊ฒฐ๊ณผ
1323
undefined 
*/
//์˜ค๋ฅ˜๋ฅผ ์žก์•„๋‚ด์ง€ ๋ชปํ•˜๊ณ  undefined๋ฅผ ์ฐ๋Š”๋‹ค.

๐ŸคจZod๋ฅผ ์–ด๋–ป๊ฒŒ ์‚ฌ์šฉํ• ๊นŒ์š”?

์œ„์˜ ์˜ˆ์‹œ๋ฅผ zod๋ฅผ ํ†ตํ•ด์„œ ์—๋Ÿฌ๋ฅผ ๋งŒ๋“ค์–ด ๋ด…์‹œ๋‹ค.

npm i zod
import { z } from "zod";

const schema = z.object({
  id: z.number(),
  name: z.string(),
});

type User = z.infer<typeof schema>;

const Json = '{"id": 1323, "username": "lurgi"}';

try {
  const user: User = schema.parse(Json);
  console.log(user.id);
  console.log(user.name);
} catch (error) {
  console.error("๋Ÿฐํƒ€์ž„ ์—๋Ÿฌ:", error);
}

/* ๋Ÿฐํƒ€์ž„ ์—๋Ÿฌ: ZodError: [
  {
    "code": "invalid_type",
    "expected": "object",
    "received": "string",
    "path": [],
    "message": "Expected object, received string"
  }
] */

๊ธฐ๋ณธ์ ์ธ ์‚ฌ์šฉ๋ฒ•์€ ์œ„์™€ ๊ฐ™์Šต๋‹ˆ๋‹ค.

zod๋ฅผ ํ†ตํ•ด ๋งŒ๋“ค์–ด์ง„ schema๋ฅผ ํ†ตํ•ด ํƒ€์ž…์„ ๋งŒ๋“ค๊ณ , parse๋ฅผ ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

๋™์ ์œผ๋กœ parse๋ฅผ ํ•˜๋Š” ๊ณผ์ •์—์„œ ํƒ€์ž… ์œ ํšจ์„ฑ์„ ๊ฒ€์‚ฌํ•  ์ˆ˜ ์žˆ๊ธฐ์— ์—๋Ÿฌ๋ฅผ ๋ฐฐ์ถœํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.


๊ธฐ๋ณธ์ ์ธ ์‚ฌ์šฉ๋ฐฉ๋ฒ•์€ ์œ„์™€ ๊ฐ™์Šต๋‹ˆ๋‹ค. ๋” ์ƒ์„ธํ•œ ์‚ฌ์šฉ๋ฒ•์„ ์ตํžˆ๊ธฐ ์œ„ํ•ด์„œ๋Š” ์•„๋ž˜ ๊ณต์‹ ๋ฌธ์„œ๋ฅผ ์ฐธ๊ณ ํ•˜์„ธ์š”!

 

GitHub - colinhacks/zod: TypeScript-first schema validation with static type inference

TypeScript-first schema validation with static type inference - GitHub - colinhacks/zod: TypeScript-first schema validation with static type inference

github.com