Schema vs Type

μŠ€ν‚€λ§ˆμ™€ νƒ€μž… λͺ¨λ‘ λ°μ΄ν„°μ˜ ꡬ쑰 및 ν˜•νƒœλ₯Ό μ •μ˜ν•˜λŠ”λ° μ‚¬μš© λ˜λŠ” ν‚€μ›Œλ“œμ΄λ‹€. 이 두 ν‚€μ›Œλ“œ κ°„μ˜ 무슨 차이가 μžˆλŠ”μ§€ ν•œλ²ˆ μ‚΄νŽ΄λ³΄μž.

Type

λ¨Όμ € νƒ€μž…μ€ 정적인 데이터 검사λ₯Ό μœ„ν•΄ μ‚¬μš© λ˜λŠ” ν‚€μ›Œλ“œμ΄λ‹€. μ—¬κΈ°μ„œ λ§ν•˜λŠ” 정적인 λ°μ΄ν„°λž€, 컴파일 νƒ€μž„μ— μ •μ˜λœ λ°μ΄ν„°μ˜ ꡬ쑰와 ν˜•νƒœλ₯Ό μ˜λ―Έν•œλ‹€. μš°λ¦¬κ°€ μ½”λ“œλ₯Ό μž‘μ„±ν•˜λ©° μ‚¬μš© λ˜λŠ” μ—¬λŸ¬ λ³€μˆ˜, ν•¨μˆ˜ λ“±μ˜ 객체의 데이터 νƒ€μž…μ„ λͺ…μ‹œν•˜μ—¬ νƒ€μž… μ•ˆμ •μ„±μ„ 높인닀. λŸ°νƒ€μž„μ΄ μ•„λ‹Œ 컴파일 νƒ€μž„μ— 검사λ₯Ό ν•˜κΈ° λ•Œλ¬Έμ— κ°œλ°œμžκ°€ 미리 νƒ€μž… μ—λŸ¬λ₯Ό ν™•μΈν•˜κ³  μž‘μ•„λ‚Όμˆ˜ μžˆλ‹€.

type User = {
    name: string;
    age: number;
}

const sampleUser : User = {
    name: 'aug',
    age: 20
}

Schema

이에 λ°˜ν•΄ μŠ€ν‚€λ§ˆλŠ” λŸ°νƒ€μž„ 데이터 검증을 μœ„ν•΄ μ‚¬μš© λ˜λŠ” ν‚€μ›Œλ“œμ΄λ‹€. λŸ°νƒ€μž„ 데이터 κ²€μ¦μ΄λΌλŠ” 단어 μžμ²΄κ°€ λ°”λ‘œ 와닿지 μ•Šμ„μˆ˜ μžˆλ‹€. 예λ₯Ό λ“€μ–΄, ꡬ글 검색창에 μž…λ ₯ν•˜λŠ” 데이터듀은 컴파일 νƒ€μž„μ— 쑴재 ν•˜μ§€ μ•ŠλŠ”λ‹€. μ‹€μ œλ‘œ μœ μ €κ°€ μž…λ ₯을 ν•΄μ•Ό 데이터가 μ „λ‹¬λ˜κΈ° λ•Œλ¬Έμ— μ΄λŸ¬ν•œ 데이터 듀을 λŸ°νƒ€μž„ 데이터라고 ν•œλ‹€.

λ‹€μ‹œ λŒμ•„μ™€μ„œ, μŠ€ν‚€λ§ˆλŠ” λŸ°νƒ€μž„ 데이터듀이 κ°œλ°œμžκ°€ κΈ°λŒ€ν•œ ꡬ쑰/ν˜•νƒœλ₯Ό κ°€μ§€κ³  μžˆλŠ”μ§€ ν™•μΈν•˜κΈ° μœ„ν•΄ μ‚¬μš© λ˜λŠ” ν‚€μ›Œλ“œμ΄λ‹€. 주둜 API 응닡값, 폼 μž…λ ₯ λ“±μ˜ 데이터 검증에 μ‚¬μš©λœλ‹€.

  • νƒ€μž… μŠ€ν¬λ¦½νŠΈμ—μ„œλŠ” zod λΌλŠ” 라이브러리λ₯Ό μ‚¬μš©ν•˜μ—¬ κ°•λ ₯ν•œ 데이터 μœ νš¨μ„± 검증을 μ‹€μ‹œν• μˆ˜ μžˆλ‹€.

import { z, ZodError } from "zod";

const pwdRegex: RegExp =
  /^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,15}$/;

const passwordRegexSchema = z
  .string()
  .min(8, {
    message: "λΉ„λ°€λ²ˆν˜ΈλŠ” 영문/숫자/특수문자λ₯Ό ν¬ν•¨ν•œ 8~15자리 μž…λ‹ˆλ‹€.",
  })
  .max(15, {
    message: "λΉ„λ°€λ²ˆν˜ΈλŠ” 영문/숫자/특수문자λ₯Ό ν¬ν•¨ν•œ 8~15자리 μž…λ‹ˆλ‹€.",
  })
  .regex(pwdRegex, {
    message: "특수문자 쀑 ; & % = - + < > οΌΌ λŠ” μ‚¬μš©ν•  수 μ—†μŠ΅λ‹ˆλ‹€.",
  });

type PasswordSchema = z.infer<typeof passwordRegexSchema>;

const verifyPassword = (password: PasswordSchema) => {
  try {
    const result = passwordRegexSchema.parse(password);
    console.log(`Successfully verified password: ${result}`);
  } catch (err) {
    if (err instanceof ZodError) {
      console.log(`Error Occurred: ${err.issues}`);
    }
  }
};

verifyPassword("password123!@");

Last updated