interface Car {
name: "car";
color: string;
start(): void
}
interface Mobile {
name: "mobile";
color: string;
call(): void;
}
✏️적용하기
function getGift(gift: Car | Mobile) {
//name과 color는 Car와 Mobile interface에 공통으로 있기 때문에 type 에러가 안남
console.log(gift.name);
console.log(gift.color);
//start()라는 함수는 interface 중 한 곳에만 있기 때문에 type 에러가 난다.
console.log(gift.start())
//따라서 조건문으로 분기처리 필요
if(gift.name === "car") {
gift.start();
} else {
gift.call();
}
}
Property start does not exist on type Car | Mobile Property start does not exist on type Mobile
인자로 받은 gift의 type이 unoin type으로 Car 또는 Mobile로 지정되어있다.(or의 의미)