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;
}
// ์๋ต
}