MST

星途 面试题库

面试题:TypeScript 如何实现复杂的复合类型嵌套及类型保护

假设你正在开发一个电商产品展示模块,产品可能是普通商品、促销商品或限量版商品。普通商品有价格和名称属性;促销商品除了价格和名称,还有折扣属性;限量版商品除了基本属性,还有库存数量属性。请使用 TypeScript 定义这些复合类型,并实现一个函数,该函数接收一个商品对象,根据商品类型执行不同操作,同时要正确使用类型保护确保代码安全。
41.9万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
// 定义普通商品类型
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);