TypeScript 브랜드 유형: 원시적 혼란 방지TypeScript 브랜드 유형: 원시적 혼란 방지

TypeScript 브랜드 유형: 원시적 혼란 방지

명목 타이핑 시뮬레이션을 위한 TypeScript 브랜드 유형(브랜드 패턴, 교차 유형, 유효성 검사 기능, ID, 통화 및 이메일 사용 사례)에 대해 자세히 알아보세요.

TypeScript는 구조적 유형 지정(오리 유형 지정)을 사용합니다. 동일한 모양을 가진 두 유형은 상호 교환 가능합니다. 이로 인해 기본 유형이 도메인 개념을 되돌릴 때 버그가 발생합니다. 즉, orderId가 필요한 곳에 userId를 전달하고 둘 다 string으로 입력됩니다. 이메일을 보냈지만 실수로 주소 대신 데이터베이스 ID를 받는 함수를 생각해 보세요. 둘 다 ‘문자열’이기 때문입니다. 브랜드 유형은 런타임 비용 없이 컴파일 타임에 구조적으로 동일한 유형을 구별하는 팬텀 유형 마커를 추가하여 이 문제를 해결합니다.

브랜드 패턴

핵심 기술은 팬텀 브랜드 속성과 교차 유형을 사용합니다.

type Brand<T, B> = T & { __brand: B };

type UserId = Brand<string, "UserId">;
type OrderId = Brand<string, "OrderId">;
type Email = Brand<string, "Email">;

__brand 속성은 런타임에 존재하지 않으며 컴파일 중에 삭제됩니다. TypeScript는 브랜드가 다르기 때문에 UserId와 OrderId를 별개의 유형으로 처리합니다.

function getUser(id: UserId): User { /* ... */ }
function getOrder(id: OrderId): Order { /* ... */ }

const uid = "user_123" as UserId;
const oid = "ord_456" as OrderId;

getUser(uid); // OK
getUser(oid); // Type error: 'OrderId' is not assignable to 'UserId'

런타임 할당 문제를 방지하려면 ‘선언’을 사용하거나 브랜드 속성을 선택 사항으로 만드세요.

// Better: unique symbol brand prevents accidental casting
declare const UserIdBrand: unique symbol;
type UserId = string & { [UserIdBrand]: true };

declare const OrderIdBrand: unique symbol;
type OrderId = string & { [OrderIdBrand]: true };

유형 가드 및 검증 기능

브랜드는 런타임에 존재하지 않으므로 시스템 경계(API 엔드포인트, 데이터베이스 결과, 양식 제출)에서 값을 검증하고 브랜드화해야 합니다.

// Factory function with validation
function createUserId(value: string): UserId {
  if (!/^user_[a-f0-9]{24}$/.test(value)) {
    throw new Error(`Invalid UserId format: ${value}`);
  }
  return value as UserId;
}

// Type guard
function isUserId(value: string): value is UserId {
  return /^user_[a-f0-9]{24}$/.test(value);
}

// Assertion function
function assertUserId(value: string): asserts value is UserId {
  if (!isUserId(value)) {
    throw new Error(`Expected a valid UserId, got: ${value}`);
  }
}

복합 유형에 대한 유효성 검사기를 작성하고 역직렬화를 처리합니다.

interface User {
  id: UserId;
  email: Email;
  name: string;
}

function parseUser(data: unknown): User {
  const raw = data as Record<string, unknown>;
  return {
    id: createUserId(String(raw.id)),
    email: createEmail(String(raw.email)),
    name: String(raw.name),
  };
}

도메인 프리미티브 사용 사례

브랜드 유형은 원시적 혼란으로 인해 실질적인 피해가 발생하는 영역에서 빛을 발합니다.

도메인브랜드 유형방지
전자상거래UserId, OrderId, ProductId교차 ID 할당 오류
핀테크USD, JPY, EUR통화 산술 실수
헬스케어PatientId, ProviderId, ClaimId환자간 데이터 유출
SaaSApiKey, SessionToken자격 증명 오용

통화 처리는 주목할만한 예입니다.

type USD = Brand<number, "USD">;
type JPY = Brand<number, "JPY">;

function addUSD(a: USD, b: USD): USD {
  return (a + b) as USD;
}

function addJPY(a: JPY, b: JPY): JPY {
  return (a + b) as JPY;
}

const price: USD = 29.99 as USD;
const tax: USD = 3.00 as USD;
const yenAmount: JPY = 5000 as JPY;

addUSD(price, tax);       // OK
addUSD(price, yenAmount); // Type error: 'JPY' not assignable to 'USD'

일반 브랜드 유형 및 라이브러리

일반적인 브랜드 패턴에 대한 일반 유틸리티를 만듭니다.

type Entity<T extends string> = Brand<string, T>;

interface Repository<T, TId extends string> {
  findById(id: Entity<TId>): Promise<T>;
  save(entity: T): Promise<void>;
}

// Usage with Zod for runtime validation + branding
import { z } from "zod";

const UserIdSchema = z.string().brand("UserId");
type UserId = z.infer<typeof UserIdSchema>;

const userRepo: Repository<User, "UserId"> = {
  async findById(id) {
    // Type-safe database query
    return db.query("SELECT * FROM users WHERE id = $1", [id]);
  },
  async save(user) { /* ... */ },
};
도서관브랜딩 접근 방식런타임 비용
타입 페스트불투명<T, 토큰>제로
io-ts브랜드 코덱유효성 검사만
‘조드’.brand() 메소드유효성 검사만
매뉴얼교차점 유형제로

성능 및 마이그레이션

브랜드 유형에는 런타임 오버헤드가 없습니다. 브랜드 속성은 컴파일 중에 지워집니다. 유효성 검사 기능은 런타임 비용을 추가하므로 시스템 경계에서 한 번 유효성을 검사하고 내부 코드베이스를 통해 브랜드 유형을 전파합니다.

// Validate at boundary, propagate internally
async function handleRequest(rawId: string) {
  const userId = createUserId(rawId); // Validate once
  const user = await userRepo.findById(userId);
  await sendEmail(user.email, welcomeMessage);
  // userId and user.email are branded — type-safe throughout
}

점진적 마이그레이션: 가장 중요한 도메인 기본 요소(ID, 통화 금액)로 시작하고, 모듈 경계에 브랜드 유형을 추가하고, 린트 규칙을 적용합니다. 전면적인 마이그레이션보다는 새로운 코드로 시작하거나 한 번에 하나의 모듈을 리팩터링하세요.

브랜드 유형은 무료 컴파일 시간 안전성을 제공하고, 유형을 통해 도메인 의미를 전달하여 코드 가독성을 향상시키며, 전체 버그 클래스를 방지합니다. 안전상의 이점은 사소한 장황성 비용보다 훨씬 큽니다. 이를 시스템 경계에 통합하고 유형 검사기가 도메인 논리를 보호하도록 하세요.