首页 > 解决方案 > 打字稿:使用 UNION 运算符时出错

问题描述

我在 Typescript 中使用 OR 运算符来定义产品可以是ProductIOR类型CartResponseInterface.Product

结构为

product: ProductI | CartResponseInterface.Product

但是当我试图获取 id 并将其存储在一个变量productId中时

productId= product.id || product.productId

我得到下面提到的错误

Error:1
Property 'id' does not exist on type 'ProductI | Product'.
Property 'id' does not exist on type 'Product'.ts(2339)

Error2:
Property 'productId' does not exist on type 'ProductI | Product'.
Property 'productId' does not exist on type 'ProductI'.ts(2339)

产品模型.ts

export interface ProductI {
  id?: string;
  name: string;
  price: number;
  .
  .
  .
}

购物车-response.model.ts

export interface Product {
  productId: string;
  name: string;
  totalPrice: number;
  .
  .
  .
}

有人可以告诉我如何解决这个问题吗?

标签: javascriptangulartypescript

解决方案


您可以使用类型断言来强制类型,然后检查产​​品的 id。

const productId = (product as ProductI).id || (product as Product).productId;
// or
const productId = (<ProductI>product).id || (<Product>product).productId;

话虽如此,除非您必须这样做,否则我不建议这样做。应该有更好的方法来利用 Typescript 的类型。


推荐阅读