서로소 - 겹치는게 하나도 없음

type Customer= {
    name:string;
    point:number;
}

type Admin= {
    name:string;
    sale:number
}

type Food = {
    name:string;
    price:number;
}

type Super = Customer | Admin | Food ;

function cart(super:Super){
    if("point" in super ) {
    	console.log(`${ super.name} 의 포인트는 ${super.point} 점이다`)
    } else if ("sale" in super) {
    	console.log(`${super.name}의 판매량은 ${super.sale}이다.`)
    } else {
    	console.log(``${super.name}의 가격은 ${super.price} )
    }
}

 

📌문제점

코드가 길어질 경우 타입의 프로퍼티만 보고 어느 타입인지 알기가 어려움

프로퍼티 네임이 변경될 경우 모든 코드 수정이 필요, 오류발생 가능성 올라감

 

📌해결법

각 타입에 태그 프로퍼티를 추가해서 서로소 관계로 만든다.

type Customer= {
    tag: "CUSTOMER"
    name:string;
    point:number;
}

type Admin= {
    tag: "ADMIN"
    name:string;
    sale:number
}

type Food = {
    tag:"FOOD"
    name:string;
    price:number;
}

 

이제 Customer 타입이면서 동시에 Admin 타입인 경우는 없다. 각각의 tag 프로퍼티에 들어간 값은 고유값이기때문.

집합 도형의 개념을 떠올려보면 Customer, Admin, Food 타입은 교집합을 그리지 않고 각각 독립된 동그라미 형태로 존재한다.

function cart(super:Super){
    if(super.tag === " CUSTOMER") {
    	console.log(`${ super.name} 의 포인트는 ${super.point} 점이다`)
    } else if (super.tag === " ADMIN") {
    	console.log(`${super.name}의 판매량은 ${super.sale}이다.`)
    } else {
    	console.log(``${super.name}의 가격은 ${super.price} )
    }
}

 

+ Recent posts