打字稿:使用UNION运算符时出现错误

时间:2020-02-21 05:59:26

标签: javascript angular typescript

我在Typescript中使用OR运算符定义乘积类型可以为ProductICartResponseInterface.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)

product.model.ts

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

cart-response.model.ts

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

有人可以告诉我如何解决吗?

2 个答案:

答案 0 :(得分:2)

您可以使用Type Assertion来强制类型,然后检查产​​品的ID。

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

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

答案 1 :(得分:-2)

https://stackblitz.com/edit/typescript-interface-inheritance

import "./style.css";

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

export interface ProductI extends Product {
  customPropI?: number;
}

export interface ProductII extends Product {
  customPropII?: number;
}

const p1 = {
  id: "23",
  name: "tmep",
  price: 140,
};

const p2 = {
  id: "23",
  name: "tmep",
  price: 140,
  customPropII: 280
};

// test1
let customId = p1.id;

// test2
let customProp = null;
if((p2 as ProductI).customPropI) customProp = (p2 as ProductI).customPropI;
else if((p2 as ProductII).customPropII) customProp = (p2 as ProductII).customPropII;

const appDiv: HTMLElement = document.getElementById("app");
appDiv.innerHTML = customProp;