当可以有任何一种时,如何处理模型中的 Typescript 类型? 更新:product 可以是 Product 或 string 类型

问题描述

根据模型的业务逻辑将具有扩展的实体或仅模型中的 id。例如,

class Order{
id:string;
product:Product
}
class Product{
id:string;
name:string;
price:number:
}

现在在订单响应中,如果我没有请求完整的数据,产品将是扩展对象或 id。那么我如何在我的 ts 模型中处理这些?是在订单模型上使用 union 的良好做法还是我应该有两个不同的模型?

解决方法

目前问题不清楚。

  1. 无论如何,如果不需要类的功能,我建议改用 TS interface。它支持类型检查,没有类的“膨胀”。

  2. 话虽如此,您可以将属性定义为 optional using ?:。然后可以将对象定义为该接口的类型,而无需可选属性。

interface Order {
  id: string;
  product?: Product;   // <-- `product` is optional
}

interface Product {
  id: string;
  name: string;
  price: number;
}

示例

const order: Order = { id: 'sample',product: {...} };  // <-- works
const order2: Order = { id: 'sample' };  // <-- works too

更新:product 可以是 Productstring 类型

您可以使用联合类型将类型定义为 Productstring

interface Order {
  id?: string;
  product?: Product | string;
}
,

然后让产品像

产品:字符串 |产品;

希望我理解你的问题!