extends와 제너릭을 활용한 조건부 타입
🔍 내용 (151쪽)
PayMethod
타입은 제너릭 타입으로extends
를 사용한 조건부 타입이다.
type PayMethod<T> = T extends "card" ? Card : Bank;
🎉 이렇게 개선하면 어떨까요?
// 전
export type PointInfo = {
saleAmount: number;
saleProducts: string;
saleType: SaleType;
savePoint: number;
saveStamp: number;
type: string;
usePoint: number;
useStamp: number;
visitedAt: string;
};
// 후
type SaleType = "point" | "stamp";
type BasePointInfo<T extends SaleType> = {
saleAmount: number;
saleProducts: string;
saleType: T;
visitedAt: string;
};
type PointInfoExtended<T extends SaleType> = BasePointInfo<T> & {
type: T;
savePoint: T extends "point" ? number : 0;
usePoint: T extends "point" ? number : 0;
saveStamp: T extends "stamp" ? number : 0;
useStamp: T extends "stamp" ? number : 0;
};
// point 타입의 예시
const pointInfo: PointInfoExtended<"point"> = {
saleAmount: 100,
saleProducts: "Product A",
saleType: "point",
savePoint: 10,
usePoint: 20,
saveStamp: 0,
useStamp: 0,
type: "point",
visitedAt: "2024-03-14",
};