面试题答案
一键面试// 定义普通商品类型
type NormalProduct = {
name: string;
price: number;
type: 'normal';
};
// 定义促销商品类型
type PromotionProduct = {
name: string;
price: number;
discount: number;
type: 'promotion';
};
// 定义限量版商品类型
type LimitedEditionProduct = {
name: string;
price: number;
stock: number;
type: 'limited';
};
// 联合类型表示所有商品类型
type Product = NormalProduct | PromotionProduct | LimitedEditionProduct;
// 根据商品类型执行不同操作的函数
function handleProduct(product: Product) {
if (product.type === 'normal') {
console.log(`普通商品: ${product.name}, 价格: ${product.price}`);
} else if (product.type === 'promotion') {
console.log(`促销商品: ${product.name}, 原价: ${product.price}, 折扣: ${product.discount}`);
} else if (product.type === 'limited') {
console.log(`限量版商品: ${product.name}, 价格: ${product.price}, 库存: ${product.stock}`);
}
}
你可以这样调用这个函数:
const normalProduct: NormalProduct = { name: '普通杯子', price: 10, type: 'normal' };
const promotionProduct: PromotionProduct = { name: '促销T恤', price: 50, discount: 0.8, type: 'promotion' };
const limitedEditionProduct: LimitedEditionProduct = { name: '限量版球鞋', price: 1000, stock: 10, type: 'limited' };
handleProduct(normalProduct);
handleProduct(promotionProduct);
handleProduct(limitedEditionProduct);