Exhaustiveness = 침착함, 완전함.
Exhaustiveness Checking
: 모든 케이스에 대해 철저하게 타입을 검사하는 것.
( 타입 좁히기에 사용되는 패러다임 중 하나 )
타입 가드 사용 -> 타입에 대한 분기 처리 수행 -> 필요하다고 생각되는 부분만 분기 처리 -> 요구 사항에 맞는 모드 작성 가능.
but, 모든 케이스에 대해 분기 처리 해야만 유지보수 측면에서 안전하다고 생각되는 상황.
: Exhaustiveness Checking을 통해 모든 케이스에 대한 타입 검사 강제 가능.
.
.
.
type ProductPrice = "10000" | "20000";
const getProductName = (productPrice: ProductPrice): string => {
if (productrice === "10000") return "배민상품권 1만 원";
if (productprice === "2000") return "배민상품권 2만 원";
else {
return "배민상품권";
}
};
type ProductPrice = "10000" | "20000" | "5000";
const getProductName = (productPrice: ProductPrice): string => {
if (productrice === "10000") return "배민상품권 1만 원";
if (productprice === "2000") return "배민상품권 2만 원";
if (productprice ==="5000") return "배민상품권 5천 원"; // 조건 추가 필요
else {
return "배민상품권";
}
};
getProductName 함수도 함께 업데이트되어야 함.
productPrice가 "5000"일 경우의 조건도 검사 -> 의도한 대로 상품권 이름을 반환해야 함.
but, getProductName 함수를 수정하지 않아도 별도 에러가 발생하는 것이 아니기 때문에 실수할 여지가 있음.
ttype ProductPrice = "10000" | "20000" | "5000";
const getProductName = (productPrice: ProductPrice): string => {
if (productrice === "10000") return "배민상품권 1만 원";
if (productprice === "2000") return "배민상품권 2만 원";
// if (productprice ==="5000") return "배민상품권 5천 원";
else { exhaustiveCheck(productPrice); // Error: Argument of type 'string' is not assign able to parameter of type 'never'
return "배민상품권";
}
};
const exhaustiveCheck = (param: never) => {
throw new Error("type error!");`
};
-> " Exhaustiveness Checking " : 이런 식으로 모든 케이스에 대한 분기 처리를 해주지 않았을 때, 컴파일타임 에러가 발생 하는 것
-> 이렇게 " Exhaustiveness Checking "을 활용하면 예상치 못한 런타임 에러를 방지하거나 요구 사항이 변경되었을 때 생길 수 있는 위험성을 줄일 수 있음.
도서참조 : 우아한 타입스크립트 with 리액트