TypeScript Union Type - ChoDragon9/posts GitHub Wiki

λŒ€μˆ˜ν•™μ€ 수λ₯Ό λŒ€μ‹ ν•΄μ„œ 문자λ₯Ό μ‚¬μš©ν•˜λŠ” 방법을 μ˜λ―Έν•œλ‹€. λŒ€ν‘œμ μœΌλ‘œ 방정식이 μžˆλ‹€. x + 10 = 15 일 λ•Œ xλŠ” 5이닀.

λŒ€μˆ˜μ  νƒ€μž…(Algebraic Data Type)은 λ‘κ°œ μ΄μƒμ˜ μžλ£Œν˜•μ˜ 값을 κ°€μ§€λŠ” μžλ£Œν˜•μ΄λ‹€. λŒ€μˆ˜μ  νƒ€μž…μ„ μ‚¬μš©ν•˜λŠ” μ–Έμ–΄λŠ” νŒ¨ν„΄ 맀칭을 톡해 μžλ£Œν˜•μ˜ μƒμ„±μžλ₯Ό 얻을 수 μžˆλ‹€.

Union Type μ •μ˜

Union Type은 TypeScriptμ—μ„œ λŒ€μˆ˜μ  νƒ€μž…μ„ μ •μ˜ν•˜λŠ” 방법이닀. Union Type은 λ‘κ°œ μ΄μƒμ˜ μžλ£Œν˜•μ˜ 값을 κ°€μ§€λŠ” μžλ£Œν˜•μ΄λ‹€. λ‘κ°œ μ΄μƒμ˜ μžλ£Œν˜•μ„ 가지기 λ•Œλ¬Έμ— νƒ€μž… μ •μ˜ μ‹œ λ‘κ°œ μ΄μƒμ˜ νƒ€μž…λ“€μ„ μ‘°ν•©ν•΄μ„œ μ •μ˜ν•œλ‹€.

λ‹€μˆ˜μ˜ μžλ£Œν˜•μ΄ 있으면,

interface Square {
  kind: 'square'
  size: number
}
interface Rectangle {
  kind: 'rectangle'
  width: number
  height: number
}
interface Circle {
  kind: 'circle'
  radius: number
}

Union Type은 μ΄λ ‡κ²Œ μ •μ˜ν•œλ‹€.

type Shape = Square | Rectangle | Circle

Union Type μ‚¬μš©

λŒ€μˆ˜μ  νƒ€μž…μ„ λ‹€λ£¨λŠ” μ–Έμ–΄μ—μ„œλŠ” νŒ¨ν„΄ 맀칭을 톡해 μžλ£Œν˜•μ„ κ΅¬λΆ„ν•œλ‹€. 예λ₯Ό λ“€μ–΄ Shapeλ₯Ό μ‚¬μš©ν•  λ•Œ, Square, Rectangle, Circle 쀑 μ–΄λ–€ μžλ£Œν˜•μΈμ§€ λΆ„κΈ° ν›„ μ‚¬μš©ν•œλ‹€.

ν•˜μ§€λ§Œ TypeScriptλŠ” 아직 νŒ¨ν„΄ 맀칭을 μ§€μ›ν•˜μ§€ μ•ŠκΈ° λ•Œλ¬Έμ— 직접 값을 ν™•μΈν•΄μ„œ μžλ£Œν˜•μ„ κ΅¬λΆ„ν•œλ‹€. 이 λ•Œ TypeScriptλŠ” νƒ€μž… 좔둠을 톡해 각 μžλ£Œν˜•μ„ μΆ”λ‘ ν•˜κ²Œ λœλ‹€.

const area = (shape: Shape) => {
  switch (shape.kind) {
    case 'square': return shape.size * shape.size;
    case 'rectangle': return shape.height * shape.width;
    case 'circle': return Math.PI * shape.radius ** 2;
  }
}

Union Type μ‚¬μš© 예

λ¨Όμ € Union Type을 μ‚¬μš©ν•˜μ§€ μ•Šμ„ λ•Œ 상황이닀. Rectangle μžλ£Œν˜•μ„ μ‚¬μš©ν•˜λŠ” Sketchbook ν΄λž˜μŠ€κ°€ μžˆλ‹€. clear λ©”μ†Œλ“œλ₯Ό 톡해 rectangleλ₯Ό λΉ„μš΄λ‹€.

interface Rectangle {
  width: number
  height: number
}

class Sketchbook {
  private rectangle: Rectangle
  constructor(rectangle: Rectangle) {
    this.rectangle = rectangle
  }
  clear() {
    this.rectangle = {
      width: 0,
      height: 0
    }
  }
}

rectangle의 μžλ£Œν˜•μ„ λΉ„μ›Œ ν• λ‹Ήν•  경우 μ΄λŸ¬ν•œ 단점이 μžˆλ‹€.

  • μžλ£Œν˜•μ— ν”„λ‘œνΌν‹°κ°€ μΆ”κ°€ μ‹œ: clear λ©”μ†Œλ“œμ— ν”„λ‘œνΌν‹°λ₯Ό μΆ”κ°€
  • μžλ£Œν˜•μ΄ λΉ„μ›Œμ‘ŒμŒμ„ 확인: 각 ν”„λ‘œνΌν‹°μ˜ 값을 확인

μ΄λ²ˆμ—λŠ” Union Type으둜 λΉ„μ›Œμ‘ŒμŒμ„ μ˜λ―Έν•˜λŠ” νƒ€μž…μ„ ν• λ‹Ήν•œ κ²½μš°μ΄λ‹€. λΉ„μ›Œμ‘Œμ„ λ•Œ null νƒ€μž…μ„ μ‚¬μš©ν•œλ‹€.

interface Rectangle {
  width: number
  height: number
}

type Empty = null

class Sketchbook {
  private rectangle: Rectangle | Empty
  constructor(rectangle: Rectangle) {
    this.rectangle = rectangle
  }
  clear() {
    this.rectangle = null
  }
}

Union Type을 μ‚¬μš©ν•˜κΈ° μ „κ³Ό λΉ„κ΅ν–ˆμ„ λ•Œ μ΄λŸ¬ν•œ μž₯점이 μžˆλ‹€.

  • μžλ£Œν˜•μ— ν”„λ‘œνΌν‹°κ°€ μΆ”κ°€ μ‹œ: null둜 ν• λ‹Ή
  • μžλ£Œν˜•μ΄ λΉ„μ›Œμ‘ŒμŒμ„ 확인: null 체크