[TS] Syntax | 06. Union & Intersection

2024. 6. 28. 17:46·Language/TypeScript

Union

Union은 두 개 이상의 타입을 동시에 받을 때 사용합니다.

enum ClothingSize {
  S = 'S',
  M = 'M',
  L = 'L',
  XL = 'XL',
}

interface Product {
  id: string;
  name: string;
  price: number;
  membersOnly?: boolean;
}

interface ClothingProduct extends Product {
  sizes: ClothingSize[];
  color: string;
}

interface ShoeProduct extends Product {
  sizes: number[];
  handmade: boolean;
}

위에서 정의된 두 가지 interface 타입은 공통된 요소가 있지만 size, color, handmade 등 서로 다른 요소도 가지고 있습니다.

이들을 모두 입력 타입으로 받은 함수를 만들고자 한다면,

ClothingProduct와 ShoeProduct를 union 하여 입력 타입을 정의할 수 있습니다.

// 두 가지 타입의 값을 모두 받을 수 있습니다.
function printSizes(product: ClothingProduct | ShoeProduct) {
  const availableSizes = product.sizes.join(', ');
  console.log(`available sizes are : ${availableSizes}`);
  
  // color 변수를 가진 타입일 때만 실행됩니다.
  if ('color' in product) {
  	console.log(`the color is : ${product.color}`);
  }
  // handmade 변수를 가진 타입일 때만 실행됩니다.
  if ('handmade' in product) {
  	console.log(product.handmade ? 'this is a handmade' : 'this is not a handmade';
  }
}

enum 타입 또한 타입 별칭과 union으로 정의할 수 있습니다.

type ClothSize = 'S' | 'W' | 'L' | 'XL';

Intersection

Intersection은 두 개 이상의 타입을 하나로 합칠 때 사용합니다.

interface Product {
  id: string;
  name: string;
  price: number;
  membersOnly?: boolean;
}

interface User {
  id: string;
  username: string;
  email: string;
  createdAt: Date;
  updatedAt: Date;
}

interface Review {
  id: string;
  productId: string;
  userId: string;
  content: string;
  createdAt: Date;
  updatedAt: Date;
}

위에서 정의된 세 가지 interface 타입들은 서로 중복되는 요소들이 있습니다.

이를 별로도 분리해서 새로운 interface 타입으로 정의하고,

이들을 Product, User, Review 타입과 intersection 시키면 짧고 간단하게 타입을 정의할 수 있습니다.

interface Id {
    id: string;
}

interface Timestamp {
    createdAt: Date;
    updatedAt: Date;
}

type Product = Id & {  // id 가 추가됩니다.
  name: string;
  price: number;
  membersOnly?: boolean;
}

type User = Id & Timestamp & {  // id, createdAt, updatedAt 이 추가됩니다.
  username: string;
  email: string;]
}

type Review = Id & Timestamp & {  // id, createdAt, updatedAt 이 추가됩니다.
  productId: string;
  userId: string;
  content: string;
}

intersection은 상속으로도 구현할 수 있습니다.

interface Entity{
    id: string
}

interface TimestapEntity extends Entity {
    createdAt: Date;
    updatedAt: Date;
}

interface Product extends Entity {
    name: string;
    price: number;
    membersOnly?: boolean;
}

interface User extends TimestapEntity {
    username: string;
    email: string;

}

interface Review extends TimestapEntity {
    productId: string;
    userId: string;
    content: string;
}
728x90

'Language > TypeScript' 카테고리의 다른 글

[TS] Type | 03. Record  (0) 2024.07.10
[TS] Syntax | 07. keyof & typeof  (0) 2024.07.10
[TS] Syntax | 05. 타입 별칭(Type Alias)  (0) 2024.06.28
[TS] Type | 02. Literal 타입  (0) 2024.06.28
[TS] Syntax | 04. Interface  (0) 2024.06.28
'Language/TypeScript' 카테고리의 다른 글
  • [TS] Type | 03. Record
  • [TS] Syntax | 07. keyof & typeof
  • [TS] Syntax | 05. 타입 별칭(Type Alias)
  • [TS] Type | 02. Literal 타입
Rayi
Rayi
  • Rayi
    아카이브
    Rayi
  • 전체
    오늘
    어제
    • 분류 전체보기 (276)
      • CS (40)
        • CV (2)
        • PS (34)
      • Reveiw (18)
        • Paper (18)
        • Github (0)
      • ML (8)
        • Pytorch (5)
      • Language (59)
        • Python (8)
        • JavaScript (32)
        • TypeScript (16)
        • C++ (3)
      • IDE (12)
      • Git (13)
      • Frontend (77)
        • React (8)
        • ReactNative (6)
        • SolidJS (20)
        • CSS (12)
      • Backend (44)
        • DB (18)
        • Node.js (11)
      • UI (3)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    vscode
    deploy
    backend
    PyTorch
    expo
    nodejs
    js
    postgresql
    mongo
    CSS
    Express
    API
    CV
    PRISMA
    review
    modal
    python
    ps
    ML
    frontend
    Git
    GAN
    ReactNative
    ts
    Three
    figma
    SOLID
    DB
    CS
    react
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.5
Rayi
[TS] Syntax | 06. Union & Intersection
상단으로

티스토리툴바