Машинопись: получение ошибки при использовании оператора UNION - PullRequest
0 голосов
/ 21 февраля 2020

Я использую оператор ИЛИ в Typescript, чтобы определить, что продукт может иметь тип ProductI ИЛИ CartResponseInterface.Product

Структурирован как

product: ProductI | CartResponseInterface.Product

Но когда я пытаюсь получить идентификатор и сохранить его в переменной 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;
  .
  .
  .
}

корзина -response.model.ts

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

Может кто-нибудь сказать мне, как решить эту проблему?

Ответы [ 2 ]

2 голосов
/ 21 февраля 2020

Вы можете использовать Введите Assertion , чтобы принудительно ввести тип, а затем проверить идентификатор продукта.

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

С учетом вышесказанного я бы не советовал делать это, если вам не нужно. Должен быть лучший способ использовать типы Typescript.

0 голосов
/ 21 февраля 2020

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;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...