유니온 타입은 하나의 변수에 여러 개의 타입을 정의하고 싶은 경우에 사용을 한다.
유니온 타입 예시
interface Car {
name: "car";
color: string;
start(): void;
}
interface Mobile {
name: "mobile";
color: string;
call(): void;
}
// 식별 가능한 유니온 타입
function getGift(gift: Car | Mobile){
console.log(gift.color);
if(gift.name == "car") {
gift.start(); // gift에 마우스를 올리면 car 인 걸 알수 있음
} else{
gift.call(); // gift에 마우스를 올리면 mobile 인 걸 알수 있음
}
}
참고강의:https://www.youtube.com/watch?v=QZ8TRIJWCGQ&list=PLZKTXPmaJk8KhKQ_BILr1JKCJbR0EGlx0&index=5
'프로그래밍 > TypeScript' 카테고리의 다른 글
[TS] Class : Constructor(생성자) & Access Modifiers (0) | 2024.03.08 |
---|---|
[TS] 교차 타입 (Intersection Types) (0) | 2024.03.06 |
[TS] 리터럴 타입 (Literal Types) (0) | 2024.03.06 |
[TS] 함수 - bind 및 오버로드 이용 (0) | 2024.03.06 |
[TS] 함수 (0) | 2024.03.06 |