MST

星途 面试题库

面试题:TypeScript联合类型在复杂业务场景下的数据处理与错误预防

假设你正在开发一个电商系统,有一个商品对象数组`let products: (ProductA | ProductB)[];`,其中`ProductA`和`ProductB`是两个不同的接口类型,`ProductA`有属性`id: number; name: string; price: number; category: 'electronics';`,`ProductB`有属性`id: number; name: string; price: number; category: 'clothes'; discount: number;`。现在要求实现一个函数,该函数能计算出所有商品的总价格,并且如果商品是`ProductB`类型,要应用折扣(价格 * (1 - 折扣率))。同时,在计算过程中如果遇到任何类型错误(比如属性不存在等情况),要抛出一个自定义的错误并进行合理处理,最终返回总价格。请用TypeScript实现整个逻辑。
16.9万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
interface ProductA {
    id: number;
    name: string;
    price: number;
    category: 'electronics';
}

interface ProductB {
    id: number;
    name: string;
    price: number;
    category: 'clothes';
    discount: number;
}

class PriceCalculationError extends Error {
    constructor(message: string) {
        super(message);
        this.name = 'PriceCalculationError';
    }
}

function calculateTotalPrice(products: (ProductA | ProductB)[]): number {
    let totalPrice = 0;
    for (const product of products) {
        if ('discount' in product) {
            if (typeof product.price!== 'number' || typeof product.discount!== 'number') {
                throw new PriceCalculationError('Price or discount is not a valid number');
            }
            totalPrice += product.price * (1 - product.discount);
        } else {
            if (typeof product.price!== 'number') {
                throw new PriceCalculationError('Price is not a valid number');
            }
            totalPrice += product.price;
        }
    }
    return totalPrice;
}

你可以使用如下方式调用这个函数:

try {
    const products: (ProductA | ProductB)[] = [
        { id: 1, name: 'Laptop', price: 1000, category: 'electronics' },
        { id: 2, name: 'T - Shirt', price: 20, category: 'clothes', discount: 0.1 }
    ];
    const total = calculateTotalPrice(products);
    console.log(`Total price: ${total}`);
} catch (error) {
    if (error instanceof PriceCalculationError) {
        console.error(`Error: ${error.message}`);
    } else {
        console.error('Unexpected error:', error);
    }
}