-
카테고리
-
세부 분야
프로그래밍 언어
-
해결 여부
미해결
만약에 인터페이스 3개를 상속 받았을 경우에 타입가드를 쓴다면
21.07.21 15:50 작성 조회수 179
1
interface Samsung{
name:string;
phonenumber: number;
}
interface KIA{
name: string;
carnumber: number;
}
interface Apple{
name: string;
Applenumber: number;
}
var phone : Samsung | KIA | Apple;
function IsSamsung(typeProduct : Samsung | KIA | Apple): typeProduct is Samsung{ // 삼성이 아니라면 phone = KIA | Apple
return (typeProduct as Samsung).phonenumber !== undefined;
}
function IsKIA(typeProduct : Samsung | KIA | Apple): typeProduct is KIA{ // KIA 가 아니라면 Apple
return (typeProduct as KIA).carnumber !== undefined;
}
if(IsSamsung(phone)){
phone.phonenumber;
}else{
if(IsKIA(phone)){
phone.carnumber;
}
else{
phone.Applenumber;
}
}
답변을 작성해보세요.
2
장기효(캡틴판교)
지식공유자2021.07.24
안녕하세요 photo님, 좋은 질문 주셨네요 :) 최종적으로 사용하고 싶은 타입이 Apple인 경우에는 아래와 같이 바로 타입을 필터링해서 사용하시면 될 것 같아요 :)
if (isApple(phone)) {
// ...
}
1
photo
질문자2021.07.21
function ThreeTypeGuard(typeProduct: Samsung| KIA | Apple):any {
if((typeProduct as Samsung).phonenumber !== undefined){
return typeProduct as Samsung;
}
else if((typeProduct as KIA).carnumber !== undefined){
return typeProduct as KIA;
}
else{
return typeProduct as Apple;
}
}
phone = {
name : "abc",
//phonenumber : 123,
//carnumber : 123,
Applenumber : 123,
}
if(ThreeTypeGuard(phone)){
phone.Applenumber
}
이렇게 하면 한개 함수로 3개를 다 처리 할수 있는거 같습니다.
답변 2