// 商品规格类型
type ProductSpec = {
[key: string]: string | number | boolean;
};
// 促销活动类型
type Promotion = {
id: string;
name: string;
discount: number;
};
// 购物车中商品项类型
type CartItem = {
productId: string;
name: string;
price: number;
quantity: number;
spec: ProductSpec;
promotions: Promotion[];
};
// 购物车整体类型
type ShoppingCart = {
items: CartItem[];
};
// 计算总价函数相关类型
type CalculateTotal = (cart: ShoppingCart) => number;
// 计算总价函数实现
const calculateTotal: CalculateTotal = (cart) => {
return cart.items.reduce((total, item) => {
let itemTotal = item.price * item.quantity;
item.promotions.forEach(promo => {
itemTotal *= (1 - promo.discount);
});
return total + itemTotal;
}, 0);
};