
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;
}
// 생략
}
728x90
'프런트엔드 > 프로그래밍 언어' 카테고리의 다른 글
DOM Event의 역사와 정의 (0) | 2023.07.21 |
---|---|
JavaScript - Decorators Proposal과 실용성 (0) | 2023.07.21 |
코루틴을 사용한 지연 평가 (0) | 2023.07.14 |
async await 한장에 정리 (0) | 2023.07.14 |
Promise 한장에 정리 (0) | 2023.07.14 |