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

如何使用TypeScript实现以Product的id为键、存储产品与数量配对的类Map数据结构

TypeScript Equivalent of Java's Map<Integer, Pair<Product, Integer>>

问题描述

我定义了如下Product模型:

export class Product { 
  id: number; 
  name: string; 
  price: number; 
  url: string; 
  description: string; 
  constructor() { 
    this.id = 1; 
    this.name = ''; 
    this.price = 0.0; 
    this.url = ''; 
    this.description = ''; 
  } 
}

我希望创建一个类Map的数据结构,使用Product的id作为键,通过该键可以获取包含产品本身和数量的结构。在Java中对应的实现为:Map<Integer, Pair<Product, Integer>> = new HashMap<>();请问如何使用TypeScript实现该结构?


解决方案

TypeScript没有内置的Pair类型,但我们可以通过自定义类型结合内置的Map对象轻松实现这个需求,下面是几种常用的方案:

方案1:自定义接口 + 内置Map(推荐,可读性最高)

首先定义一个清晰的接口来表示“产品+数量”的组合,然后用Map以产品id为键存储这个结构:

// 定义包含产品和数量的接口
interface ProductWithQuantity {
  product: Product;
  quantity: number;
}

// 创建Map实例,键为number类型(对应Product的id),值为上面定义的接口
const productInventory: Map<number, ProductWithQuantity> = new Map();

使用示例:

// 实例化一个产品
const orange = new Product();
orange.id = 1;
orange.name = "Orange";
orange.price = 3.0;

// 添加到Map中
productInventory.set(orange.id, { product: orange, quantity: 8 });

// 获取产品信息
const inventoryItem = productInventory.get(1);
if (inventoryItem) {
  console.log(`产品名称:${inventoryItem.product.name},当前库存:${inventoryItem.quantity}`);
}

// 更新库存数量
if (inventoryItem) {
  inventoryItem.quantity += 2;
  productInventory.set(1, inventoryItem); // 因为对象是引用类型,也可以直接修改后不用set,但显式调用更规范
}

方案2:元组类型 + 内置Map(简洁高效)

如果觉得自定义接口有点冗余,可以直接用TypeScript的元组类型[Product, number],元组的第一个元素存产品,第二个存数量:

const productInventory: Map<number, [Product, number]> = new Map();

使用示例:

const grape = new Product();
grape.id = 2;
grape.name = "Grape";
grape.price = 5.5;

productInventory.set(grape.id, [grape, 12]);

// 解构获取产品和数量
const [product, quantity] = productInventory.get(2) || [new Product(), 0];
console.log(`产品:${product.name},数量:${quantity}`);

方案3:普通对象(适合简单场景)

如果你的产品id都是数字或字符串,也可以用普通JavaScript对象来模拟这个结构,不过要注意对象的键会被自动转为字符串:

// 用自定义接口的情况
const productInventory: Record<number, ProductWithQuantity> = {};

// 或者用元组
// const productInventory: Record<number, [Product, number]> = {};

使用示例:

productInventory[3] = { product: someProduct, quantity: 5 };
console.log(`当前库存:${productInventory[3].quantity}`);

这种方式的缺点是无法很好地处理非字符串/数字类型的键,也没有Map的has、delete等便捷方法,所以更推荐前两种方案。


内容的提问来源于stack exchange,提问作者Arefe

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 05:47:50