You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何对服务端返回的多类型Product数据及选中实例做TypeScript类型定义

类型定义方案

1. 基础产品类型定义

首先定义所有产品共享的公共属性基础接口,再基于基础接口扩展各产品的独有属性,将type字段定义为字面量类型作为类型判别标识:

// 公共属性基础接口
interface BaseProduct {
  name: string;
  description: string;
  price: number;
  type: string;
}

// 第一类产品独有属性定义
interface SomeProduct extends BaseProduct {
  type: 'someProduct';
  // 示例独有属性,可根据实际业务替换
  size: string;
  color: string;
}

// 第二类产品独有属性定义
interface SomeOtherProduct extends BaseProduct {
  type: 'someOtherProduct';
  // 示例独有属性
  shelfLife: number;
  weight: number;
}

// 第三类产品独有属性定义
interface AnotherProduct extends BaseProduct {
  type: 'anotherProduct';
  // 示例独有属性
  author: string;
  pageCount: number;
}

// 所有产品类型的联合类型
type Product = SomeProduct | SomeOtherProduct | AnotherProduct;

2. products 对象类型定义

分两种场景选择定义方式:

  • 如果你明确知道products的所有键名,建议用严格的接口定义,类型校验更严谨:
interface Products {
  someProduct: SomeProduct;
  someOtherProduct: SomeOtherProduct;
  anotherProduct: AnotherProduct;
}
  • 如果键名不固定、会动态新增,用泛型记录类型定义即可:
type Products = Record<string, Product>;

3. 选中产品变量类型定义

直接使用上面定义的联合类型Product即可,配合type字段做类型守卫,TypeScript会自动缩小类型范围,识别对应产品的独有属性:

// 选中产品变量定义,未选中时为null可根据业务调整
let selectedProduct: Product | null = null;

场景使用示例

  1. 遍历所有产品渲染公共属性,可直接访问公共字段不会报类型错误:
Object.values(products).forEach(product => {
  console.log(product.name, product.description, product.price);
})
  1. 渲染选中产品的独有属性,通过type判断即可安全访问独有字段:
if (selectedProduct) {
  switch(selectedProduct.type) {
    case 'someProduct':
      // 此处自动识别为SomeProduct类型,可直接访问size、color
      console.log(selectedProduct.size, selectedProduct.color);
      break;
    case 'someOtherProduct':
      // 此处自动识别为SomeOtherProduct类型
      console.log(selectedProduct.shelfLife, selectedProduct.weight);
      break;
    case 'anotherProduct':
      // 此处自动识别为AnotherProduct类型
      console.log(selectedProduct.author, selectedProduct.pageCount);
      break;
  }
}

内容的提问来源于stack exchange,提问作者Cristian Flórez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 11:15:01