TypeScript Union Type - The-Next-Web-Research-Lab/the-next-web-research-lab.github.io GitHub Wiki


title: TypeScript - Union Type ์ •์˜์™€ ์‚ฌ์šฉ๋ฒ• ๊ฐ„๋‹จ ์ •๋ฆฌ

TypeScript - Union Type ์ •์˜์™€ ์‚ฌ์šฉ๋ฒ• ๊ฐ„๋‹จ ์ •๋ฆฌ

Union Type ์ด๋ž€?

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์˜ ํƒ€์ž… ์ถ”๋ก 

TypeScript์—์„œ๋Š” ํƒ€์ž… ์ถ”๋ก (type inference)์„ ํ†ตํ•ด ๊ฐ ํƒ€์ž…์„ ์ถ”๋ก ํ•˜๊ฒŒ ๋œ๋‹ค. TypeScript๋ฅผ ํ™•์ธํ•ด ๋ณผ ๋•Œ๋Š” TypeScript Playground๋กœ ์˜จ๋ผ์ธ์—์„œ ํ™•์ธํ•  ์ˆ˜ ์žˆ๋‹ค.

const getArea = (shape: Shape) => {
  if (shape.kind === "square") {
    // ์—ฌ๊ธฐ์„œ Rectangle๊ณผ Circle์˜ ํ”„๋กœํผํ‹ฐ๋ฅผ
    // ์‚ฌ์šฉํ•˜๋ฉด ํƒ€์ž… ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค.
    return shape.size * shape.size;
  }
  // ์ƒ๋žต
}