MST
星途 面试题库

面试题:基于TypeScript使用问题域语言优化复杂类型命名

现有一个电商系统的购物车模块,购物车中的商品项可能有不同的规格、促销活动等复杂属性。请用TypeScript,以问题域语言精准命名购物车中商品项类型、购物车整体类型以及计算总价的函数相关类型,且要考虑类型之间的关联和约束,给出完整的TypeScript代码实现。
24.2万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
// 商品规格类型
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);
};