아카이브

[TS] Syntax | 06. Union & Intersection 본문

Language/TypeScript

[TS] Syntax | 06. Union & Intersection

Rayi 2024. 6. 28. 17:46

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  (1) 2024.07.10
[TS] Syntax | 07. keyof & typeof  (0) 2024.07.10
[TS] Syntax | 05. 타입 별칭(Type Alias)  (1) 2024.06.28
[TS] Type | 02. Literal 타입  (1) 2024.06.28
[TS] Syntax | 04. Interface  (0) 2024.06.28
Comments