面试题答案
一键面试- 定义类型别名和联合类型:
- 首先定义商品类型的基础接口,然后通过联合类型表示不同类型的商品。
// 定义商品基础接口 type BaseProduct = { id: number; name: string; price: number; }; // 促销商品接口 type PromotionProduct = BaseProduct & { discount: number; }; // 限时抢购商品接口 type FlashSaleProduct = BaseProduct & { saleEndTime: Date; }; // 联合类型表示不同类型的商品 type Product = BaseProduct | PromotionProduct | FlashSaleProduct;
- 实现根据商品类型计算总价的函数:
function calculateTotalPrice(products: Product[]): number { let total = 0; products.forEach(product => { if ('discount' in product) { total += product.price * (1 - product.discount); } else if ('saleEndTime' in product) { total += product.price; } else { total += product.price; } }); return total; }
- 使用示例:
const products: Product[] = [ { id: 1, name: '普通商品', price: 100 }, { id: 2, name: '促销商品', price: 200, discount: 0.2 }, { id: 3, name: '限时抢购商品', price: 150, saleEndTime: new Date() } ]; const totalPrice = calculateTotalPrice(products); console.log(`商品总价: ${totalPrice}`);
这样通过TypeScript的类型别名和联合类型,定义了一套类型系统来确保模块间数据交互的准确性。并且calculateTotalPrice
函数能够根据商品的不同类型执行相应的业务逻辑计算总价,提高了代码的可维护性。