강의

멘토링

커뮤니티

Cộng đồng Hỏi & Đáp của Inflearn

Hình ảnh hồ sơ của photo2226
photo2226

câu hỏi đã được viết

TypeScript từ cơ bản đến thực chiến

Giới thiệu và ứng dụng các loại bảo vệ

만약에 인터페이스 3개를 상속 받았을 경우에 타입가드를 쓴다면

Viết

·

262

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개 써서 하는게 최선일까요?
es6typescriptjavascript

Câu trả lời 2

2

captain님의 프로필 이미지
captain
Người chia sẻ kiến thức

안녕하세요 photo님, 좋은 질문 주셨네요 :) 최종적으로 사용하고 싶은 타입이 Apple인 경우에는 아래와 같이 바로 타입을 필터링해서 사용하시면 될 것 같아요 :)

if (isApple(phone)) {

  // ...

}

1

photo님의 프로필 이미지
photo
Người đặt câu hỏi

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개를 다 처리 할수 있는거 같습니다.
Hình ảnh hồ sơ của photo2226
photo2226

câu hỏi đã được viết

Đặt câu hỏi