Union Type(유니온 타입), Intersection Type(인터섹션 타입)

이민서·2025년 1월 24일

TypeScript

목록 보기
5/7

Union Type(|)

서로 다른 타입들을 결합하여 하나의 타입으로 정의

// 기본 사용
type StringOrNumber = string | number;
let value: StringOrNumber = "hello";
value = 42; // OK

// 객체 타입 Union
type Admin = {
  id: number;
  role: "admin";
};

type User = {
  id: number;
  email: string;
};

type Account = Admin | User;

function processAccount(account: Account) {
  if ("role" in account) {
    // Admin 타입
    console.log("Admin account");
  } else {
    // User 타입
    console.log("User account");
  }
}

Intersection Type(&)

여러 타입을 하나로 결합하여 모든 타입의 속성을 포함하는 새로운 타입 생성

// 기본 사용
type Employee = {
  name: string;
  id: number;
};

type Manager = {
  managerId: string;
  team: string[];
};

type TeamManager = Employee & Manager;

const manager: TeamManager = {
  name: "John",
  id: 123,
  managerId: "M123",
  team: ["Alice", "Bob"]
}; // 모든 속성 필요

// 인터페이스와 함께 사용
interface HasName {
  name: string;
}

interface HasAge {
  age: number;
}

type Person = HasName & HasAge;

주요 차이점

  • 타입 결합 방식

    • Union(|): "또는" - 타입 중 하나만 만족하면 됨
    • Intersection(&): "그리고" - 모든 타입의 속성을 만족해야 함
  • 사용 목적

    • Union(|): 여러 타입 중 하나를 선택할 때
    • Intersection(&): 여러 타입의 속성을 모두 결합할 때
  • 타입 검사

    • Union(|): 타입 가드 필요
    • Intersection(&): 모든 속성이 있어야 함

사용 예제

// Union Type 활용
type ApiResponse<T> = 
  | { status: "success"; data: T; }
  | { status: "error"; error: string; };

function handleResponse(response: ApiResponse<User>) {
  if (response.status === "success") {
    console.log(response.data.name);
  } else {
    console.error(response.error);
  }
}

// Intersection Type 활용
type BaseProps = {
  className?: string;
  style?: React.CSSProperties;
};

type ButtonProps = BaseProps & {
  onClick: () => void;
  label: string;
};

const Button = ({ onClick, label, ...props }: ButtonProps) => {

};

0개의 댓글