面试题答案
一键面试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);
}
}