Encountering an issue with the UNION operator in Typescript causes an error

Currently, I am utilizing the OR operator within Typescript to designate that a product could be of type ProductI OR CartResponseInterface.Product

This is how it is structured:

product: ProductI | CartResponseInterface.Product

However, when attempting to extract the id and assign it to a variable productId like so:

productId = product.id || product.productId

I encounter the following errors:

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

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

In my product.model.ts file:

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

In cart-response.model.ts:

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

If anyone could provide assistance on resolving this issue, it would be greatly appreciated.

Answer №1

If necessary, you can utilize Type Assertion to coerce the type and then verify the product's id.

You could try obtaining the product id using Type Assertion like this:
const productId = (product as ProductI).id || (product as Product).productId;
// or
const productId = (<ProductI>product).id || (<Product>product).productId;

However, consider alternative methods before resorting to this approach as there may be a more efficient way to leverage Typescript's types.

Answer №2

Check out this StackBlitz demo on 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 product1 = {
  id: "23",
  name: "tmep",
  price: 140,
};

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

// Testing
let customId = product1.id;

let customProp = null;
if((product2 as ProductI).customPropI) customProp = (product2 as ProductI).customPropI;
else if((product2 as ProductII).customPropII) customProp = (product2 as ProductII).customPropII;

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Assigning numerical ratings to a web-based questionnaire in HTML

In my questionnaire, I have radio buttons and checkboxes that need to be graded. The format of the input elements looks like this: <input type="radio" name="1" value="Yes" onclick="document.getElementById('pls').setAttribute('requi ...

How to showcase an image with Angular 2?

Just starting out with Angular 2 and ran into an issue while trying to display an image using a relative path. <img src="./../images/publicVideo1.PNG"> Unfortunately, I encountered the following error: null:1 GET http://localhost:4200/null 404 (No ...

Regular expressions can be used to remove specific parts of a URL that come before the domain name

Looking for some help with a javascript task involving regex and the split function. Here's what I need to achieve: Input: http://www.google.com/some-page.html Output: http://www.google.com I attempted the following code but unfortunately it didn&ap ...

Tips for manipulating the DOM: Pushing existing elements when new ones are dynamically created with JavaScript

I have a pre-existing DOM element (let's say a div) and I am using JavaScript, specifically React, to create a new element - another div which serves as a sidebar. The goal is for the sidebar to seamlessly shift the previous element without overlappin ...

Reorganizing JSON structures by incorporating unique identifiers into nested elements

I am working on restructuring an incoming JSON object to utilize in a React component. The JSON data that I'm receiving is stored in jsonData. This is the current structure of my code: const jsonData = { "Jonas": { "position": "CTO", "em ...

Is it possible to apply JavaScript object destructuring but make changes to certain values before assigning them to a new object?

After receiving movie data from an api, I am currently manually creating a new object with a subset of properties and modified values. Is there a more efficient way to achieve this using javascript/typescript object destructuring syntax? I specifically wa ...

stop the page from refreshing when clicking on the map area

http://jsbin.com/iTeNiJIt/1/edit?output I currently have multiple map areas on my webpage. When a user clicks on any of these areas, I want to create an animation without refreshing the page. However, I am facing an issue where the page refreshes every ti ...

Leverage the Express JS .all() function to identify the specific HTTP method that was utilized

My next task involves creating an endpoint at /api that will blindly proxy requests and responses to a legacy RESTful API system built in Ruby and hosted on a different domain. This is just a temporary step to transition smoothly, so it needs to work seam ...

Determine the type of a nested class within TypeScript

Utilizing nested classes in TypeScript is achieved through the following code snippet: class Parent { private secret = 'this is secret' static Child = class { public readSecret(parent: Parent) { return parent.secret } } } ...

Enhance the design of MDX in Next.js with a personalized layout

For my Next.js website, I aim to incorporate MDX and TypeScript-React pages. The goal is to have MDX pages automatically rendered with a default layout (such as applied styles, headers, footers) for ease of use by non-technical users when adding new pages. ...

Unable to use the same hexadecimal HTML entity in the value props of a React JSX component

Can someone explain why this code snippet displays dots as password and the other displays plain hexadecimal codes? <Field label="Password" value="&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;" type="password" /> While this one disp ...

Having trouble with JQuery's .prop function not unchecking a checkbox?

I have been experimenting with different solutions in order to uncheck a checkbox when another checkbox is checked. Unfortunately, none of the methods I've tried seem to be working effectively... Currently, my code looks like this: $("#chkBox1").cli ...

JavaScript's POST method is failing to fetch data from the API, yet it is able to retrieve data successfully in

I am experiencing issues when trying to retrieve data from an API using JavaScript. The API works fine in Postman, but it is not functioning properly in JavaScript. When I run the code, the console displays an error message stating "Failed to fetch respon ...

Encountered a connection error in the Spring Boot application: net::ERR_CONNECTION_REF

Currently working on a school project developing a Spring Boot application using Restful. The application runs smoothly locally, but when deployed to AWS, I am encountering an "net::ERR_CONNECTION_REFUSED" error for all my GET and POST requests sent to the ...

The soft keyboard on Android devices may be obscured by an input field when using Cordova

When I use the text input field on my Android phone, the soft keyboard covers the input field. My app is built with Cordova and Angular 6. I have attempted the following solution: <preference name="Fullscreen" value="false" /> <edit-config file ...

What is the process for transferring `Parentobject1` to `childobject2` and `childobject3` in Three.js?

I have created two objects doubleSquare and doubleSquare1. I was expecting the output to be Double Line Square Object, but I have tried two different formats and have not achieved the desired output. Can someone please provide me with a solution? I have lo ...

Incorporate the teachings of removing the nullable object key when its value is anything but 'true'

When working with Angular, I have encountered a scenario where my interface includes a nullable boolean property. However, as a developer and maintainer of the system, I know that this property only serves a purpose when it is set to 'true'. Henc ...

Tips on how to eliminate focus after choosing a radio button in Angular Material?

This is a snippet from my HTML template file, which includes two Angular Material radio buttons. My goal is to disable the focus on the rings quickly after selecting any radio button. <div id="login-form" class="vh-100 overflow-auto" ...

Creating horizontal cards with Angular MaterialWould you like to learn how to design

I need help converting these vertical cards into horizontal cards. Currently, I am utilizing the Angular Material Cards component. While I can successfully create cards in a vertical layout, my goal is to arrange them horizontally. Below is the code sni ...

Include a new button in the react material-table toolbar

I am looking to enhance the material-table toolbar by adding a new button. This button will not be directly related to the table, but instead, it will open a modal window with additional information. The button I want to add is called "quotations" and I w ...