Typescript infer 쉽게 이해하기: Zod z.infer로 배우는 타입 추론

· frontend

Intro

타입은 안전하게, 코드는 가볍게. 이 글은 TypeScript의 infer 키워드와 Zod의 z.infer를 함께 이해하면서, "런타임 검증과 타입 추론을 한 번에" 가져가는 실무 패턴을 예제로 정리합니다. 문법 소개에 그치지 않고 실제 현업에서 바로 쓸 수 있는 형태로 구성했습니다.

타입 추론(Type Inference)의 기본 개념

TypeScript는 가능한 한 자동으로 타입을 유추합니다. 명시적 타입은 줄이고, 안전성은 유지하는 것이 핵심입니다.

const count = 3; // number로 추론
let title = "Hello"; // string으로 추론

const user = { id: 1, name: "Ada" }; // { id: number; name: string }

function add(a: number, b: number) {
  return a + b; // number로 추론
}

하지만 복잡한 제네릭/조건부 타입에서는 추론만으로는 한계가 있습니다. 이 때 등장하는 것이 infer입니다.

TypeScript의 infer 키워드

infer는 조건부 타입 내에서 “타입 변수”를 추론하도록 하는 키워드입니다. 다음처럼 타입의 일부를 분해해 내부 타입을 추론할 수 있습니다.

// 배열 요소 타입 뽑아내기
type ElementType<T> = T extends (infer U)[] ? U : T;
type A = ElementType<string[]>; // string
type B = ElementType<number>; // number

// 함수의 반환 타입 추론
type ReturnTypeOf<T> = T extends (...args: any[]) => infer R ? R : never;
const toPair = (n: number) => [n, String(n)] as const;
type R = ReturnTypeOf<typeof toPair>; // readonly [number, string]

// Promise 중첩 해제
type Awaited<T> = T extends Promise<infer U> ? Awaited<U> : T;
type P = Awaited<Promise<Promise<string>>>; // string

핵심은 "조건부 타입" 안에서만 infer를 사용할 수 있고, 패턴 매칭처럼 타입을 분해한다는 점입니다.

Zod와 z.infer

Zod는 런타임에 데이터를 검증하는 스키마 라이브러리입니다. 동시에 스키마에서 TypeScript 타입을 추론할 수 있어, 검증 로직과 타입 정의를 단일 소스로 관리할 수 있습니다.

import { z } from "zod";

const UserSchema = z.object({
  id: z.number().int().positive(),
  name: z.string().min(1),
  email: z.string().email(),
  role: z.enum(["admin", "member"]).default("member"),
});

type User = z.infer<typeof UserSchema>;
// type User = { id: number; name: string; email: string; role: "admin" | "member" }

z.infer는 스키마를 단일 진실 소스로 두고 타입을 자동 생성합니다. 스키마가 바뀌면 타입도 자동으로 반영됩니다.

Zod 핵심 레시피 (실무에서 자주 쓰는 문법)

refine / superRefine: 커스텀 검증

import { z } from "zod";

const PasswordSchema = z
  .string()
  .min(8, { message: "8자 이상이어야 합니다." })
  .superRefine((val, ctx) => {
    if (!/[A-Z]/.test(val)) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        message: "대문자를 최소 1자 포함하세요.",
      });
    }
    if (!/\d/.test(val)) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        message: "숫자를 포함하세요.",
      });
    }
  });

판별 유니온(discriminatedUnion): 안전한 분기 처리

const ShapeSchema = z.discriminatedUnion("type", [
  z.object({ type: z.literal("circle"), radius: z.number().positive() }),
  z.object({
    type: z.literal("rect"),
    width: z.number().positive(),
    height: z.number().positive(),
  }),
]);

type Shape = z.infer<typeof ShapeSchema>;

function area(shape: Shape) {
  switch (shape.type) {
    case "circle":
      return Math.PI * shape.radius ** 2;
    case "rect":
      return shape.width * shape.height;
  }
}

transform / coerce / preprocess: 입력 정규화

// 문자열 숫자 → number (공백 트림 후 변환)
const NumberFromAny = z.preprocess(
  (v) => (typeof v === "string" ? v.trim() : v),
  z.coerce.number()
);

// 체인으로 후처리
const TrimmedEmail = z.string().trim().toLowerCase().email();

// 안전한 파이프 구성 (validate → transform)
const PositiveIntStringToNumber = z
  .string()
  .regex(/^\d+$/)
  .transform((s) => Number(s))
  .pipe(z.number().int().positive());

unknown 필드 처리 정책: strict / strip / passthrough

const Base = z.object({ a: z.string() });
Base.strict(); // 알 수 없는 키가 오면 에러
Base.strip(); // 알 수 없는 키 버림 (기본값)
Base.passthrough(); // 알 수 없는 키 유지

브랜드 타입(brand)로 도메인 강화

const UserId = z.string().uuid().brand<"UserId">();
type UserId = z.infer<typeof UserId>; // string & { __brand: "UserId" }

const PostId = z.string().uuid().brand<"PostId">();
type PostId = z.infer<typeof PostId>;

// 다른 브랜드끼리 혼용을 방지
function loadUser(id: UserId) {
  // ...
}

// loadUser("uuid-of-post" as PostId); // 타입 오류 유도

런타임 검증 + 타입 추론의 시너지

검증과 타입을 분리하면 다음과 같은 문제가 생깁니다.

  • 드리프트(Drift): 타입과 실제 데이터 규칙이 어긋남
  • 중복 정의: 같은 스펙을 타입과 런타임에 두 번 작성

Zod + z.infer 패턴은 이를 해결합니다.

function parseUser(input: unknown) {
  const result = UserSchema.safeParse(input);
  if (!result.success) {
    return { ok: false as const, error: result.error.flatten() };
  }
  // result.data의 타입은 자동으로 User
  return { ok: true as const, data: result.data };
}

const res = parseUser(JSON.parse('{"id":1,"name":"Ada","email":"[email protected]"}'));
if (res.ok) {
  // 여기서 res.data는 User로 안전하게 사용 가능
}

실무 예제

1) API 응답 검증 + 타입 자동화

import { z } from "zod";

const ArticleSchema = z.object({
  id: z.string().uuid(),
  title: z.string().min(1),
  summary: z.string().default(""),
  tags: z.array(z.string()).default([]),
  publishedAt: z.coerce.date().optional(), // 문자열 날짜를 Date로 변환
});

const ArticlesResponseSchema = z.object({
  items: z.array(ArticleSchema),
  nextCursor: z.string().nullable().optional(),
});

type Article = z.infer<typeof ArticleSchema>;
type ArticlesResponse = z.infer<typeof ArticlesResponseSchema>;

async function fetchArticles(cursor?: string): Promise<ArticlesResponse> {
  const url = new URL("https://api.example.com/articles");
  if (cursor) url.searchParams.set("cursor", cursor);

  const res = await fetch(url);
  const json = await res.json();

  return ArticlesResponseSchema.parse(json);
}

// 사용 예
const { items } = await fetchArticles();
items.forEach((article) => {
  // article은 Article 타입으로 안전
  console.log(article.title.toUpperCase());
});

2) 폼 입력 검증 + 에러 메시지 매핑

const SignUpSchema = z.object({
  email: z.string().email({ message: "올바른 이메일을 입력하세요." }),
  password: z
    .string()
    .min(8, { message: "비밀번호는 8자 이상이어야 합니다." })
    .regex(/[A-Z]/, { message: "대문자를 최소 1자 포함하세요." }),
  name: z.string().min(1, { message: "이름을 입력하세요." }),
});

type SignUpInput = z.infer<typeof SignUpSchema>;

function validateSignUp(input: unknown) {
  const r = SignUpSchema.safeParse(input);
  if (!r.success) return r.error.flatten().fieldErrors; // UI에 직접 매핑 가능
  return null;
}

3) 서버 환경변수 검증 (배포 사고 예방)

const EnvSchema = z.object({
  NODE_ENV: z.enum(["development", "test", "production"]),
  DATABASE_URL: z.string().url(),
  PORT: z.coerce.number().int().positive().default(3000),
});

export type Env = z.infer<typeof EnvSchema>;
export const env: Env = EnvSchema.parse(process.env);

4) 타입 안전한 fetch 래퍼 (스키마 기반)

import { z } from "zod";

async function fetchZ<TSchema extends z.ZodTypeAny>(
  input: RequestInfo | URL,
  init: RequestInit | undefined,
  schema: TSchema
): Promise<z.infer<TSchema>> {
  const res = await fetch(input, init);
  const json = await res.json();

  try {
    const parsed = schema.parse(json);
    if (!res.ok) {
      // HTTP 에러라도 스키마는 맞는 경우 → 앱 정책에 따라 처리
      throw new Error(`HTTP ${res.status}`);
    }
    return parsed;
  } catch (e) {
    if (e instanceof z.ZodError) {
      // 검증 실패 시 상세 이슈를 함께 던짐
      throw Object.assign(new Error("ValidationError"), {
        status: res.status,
        issues: e.issues,
        raw: json,
      });
    }
    throw e;
  }
}

// 사용 예시
const RepoSchema = z.object({ id: z.number(), name: z.string() });
const data = await fetchZ("/api/repo", { method: "GET" }, RepoSchema);
// data는 자동으로 { id: number; name: string }

5) 판별 유니온과 안전한 UI 분기 (React)

import { z } from "zod";

const NotificationSchema = z.discriminatedUnion("type", [
  z.object({ type: z.literal("success"), message: z.string() }),
  z.object({
    type: z.literal("error"),
    message: z.string(),
    retryable: z.boolean(),
  }),
]);

type Notification = z.infer<typeof NotificationSchema>;

function Notice({ n }: { n: Notification }) {
  switch (n.type) {
    case "success":
      return <div className="text-green-600">{n.message}</div>;
    case "error":
      return (
        <div className="text-red-600">
          {n.message}
          {n.retryable && <button>다시 시도</button>}
        </div>
      );
  }
}

한계와 고려사항

  • 런타임 비용: 대규모 응답을 잦게 파싱하면 비용이 증가할 수 있습니다. 핵심 경로만 검증하거나 캐시/샘플 검증을 고려하세요.
  • 스키마-도메인 분리: 너무 복잡한 도메인 규칙까지 스키마에 몰아넣으면 관리가 어려워집니다. 핵심 불변식만 스키마로, 나머지는 도메인 로직으로 분리하세요.
  • 변환 책임: z.coerce/transform를 남용하면 타입은 맞지만 의미가 흐려질 수 있습니다. 변환은 명확한 목적이 있을 때만.
  • 서드파티 변경: 외부 API 응답 변경에 대비해 스키마를 느슨하게 정의하고, 버전 필드로 분기하는 전략이 유용합니다.
  • 대체재 비교: class-validator, io-ts, valibot 등과 트레이드오프를 비교하세요. 팀의 러닝커브/생태계/성능 요구를 고려합니다.

Zod vs 대안 기술

항목ZodYupio-tsValibot
타입 추론z.infer로 직관적제한적강력하지만 문법 복잡Infer 제공
런타임 검증내장 parse/safeParse검증 중심Either 기반가볍고 빠름
DX체이닝, 에러 메시지 우수널리 알려짐FP 패러다임 숙련 필요간결한 API
유니온/판별 유니온지원제한적지원지원
transform/coerce지원제한적변환은 별도지원
생태계RHF, tRPC 등 연동 활발Form 위주fp-ts 연계신흥

선택 기준은 팀의 선호, 러닝 커브, 목적(폼 vs API)과 성능 요구입니다. 범용성과 DX 측면에서 Zod는 균형이 좋아 빠른 도입에 유리합니다.

도입 체크리스트

  • 경계에 스키마 배치: API 응답, 폼 입력, 환경변수부터 적용
  • strict 정책 결정: 외부 입력은 strict() 또는 strip() 정책 명확화
  • 전처리 일원화: trim, toLowerCase, coerce를 스키마에 캡슐화
  • 유니온 모델링: 상태/이벤트는 판별 유니온으로 안전한 분기 보장
  • 오류 로깅 표준화: safeParse().error.flatten() 형태로 수집/모니터링
  • 타입 동기화: 타입은 전부 z.infer에서 파생, 별도 타입 선언 최소화

참고 자료

정리 (Conclusion)

  • 핵심: Zod 스키마를 단일 소스로 두고 z.infer로 타입을 자동 생성하면, 검증과 타입의 드리프트를 제거할 수 있습니다.
  • 실무 팁: API/폼/환경변수 같은 실패 비용이 큰 경로부터 단계적으로 도입하세요.
  • 문법 포인트: 복잡한 타입 분해가 필요하면 TypeScript infer로 레고처럼 타입을 조립하세요.

이 글의 예제는 바로 복사해 사용 가능하도록 구성했습니다. 팀 컨벤션/도메인 요구에 맞춰 스키마를 얇게 시작해 점진적으로 확장해 보세요.