Step-by-step guide for inserting data into a Typescript method with an interface

I am currently working on developing a shopping cart quiz. I have successfully passed the product details from child to parent using event emitter, but I am encountering an issue when trying to add the product to the cart. The error I am facing is in the `addProduct` method below due to mismatched properties between the `Product` and `CartItem` interfaces.

addProduct(product: Product){this.cart.items.push(product)}

The error message states: (parameter) product: Product Argument of type 'Product' is not assignable to parameter of type 'CartItem'. Type 'Product' is missing the following properties from type 'CartItem': item, quantityts(2345)

 export class AppComponent {
   products: Product[];
   cart: Cart;

constructor() {
     this.cart = {
     items: []
    } as Cart
 } 

   ngOnInit() {
this.products = [...PRODUCTS].map((product, index) => {
  product.id = index + 1;
  product.image = `/assets/images/items/${product.name.toLocaleLowerCase()}.png`;
  product.cartQuantity = 0;
  return product;
});   
    
 addToCart(product: Product) {
    this.cart.items.push(product); 
   }


**cart.ts**

export interface CartItem {
  id: number;
  item: string;
 quantity: number;
 }
export interface Cart {
  items: CartItem[];
 }

**Product.ts**

 export interface Product {
    name: string;
    price: number;
    id?: number;
    image?: string;
    cartQuantity?: number;
  }
  export enum UpdateMode {
     SUBTRACT,
    ADD
  }

app.component.html

 <app-product-list [products]="products"
                (onAddToCart)="addToCart($event)"
                (onQuantityUpdate)="updateCart($event)"
                class="flex-70"></app-product-list>
 <app-cart class="flex-30" [cart]="cart"></app-cart>

How can I correctly send the product to the input property in the cart.component.ts file?

 export class CartComponent implements OnInit{
    @Input() cart: Cart;
       constructor() {}

Answer №1

Hey there, it appears that the error is occurring because you are attempting to assign a product of type Product to type Cart, which have different keys and all are required. At first glance, you can make some adjustments like this in order to resolve the issue.

    addToCart({id, name, cartQuantity}: Product) {
     let cart: CartItem = {
       id,
       item: name,
       quantity: cartQuantity
     };

    this.cart.items.push(cart); 
    console.log(this.cart)
   }

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

Style the date using moment

All languages had a question like this except for JavaScript. I am trying to determine, based on the variable "day," whether it represents today, tomorrow, or any other day. ...

I'm currently attempting to determine the total cost of a series of operations, however, I am not receiving any results

Here is the code snippet from my HTML file: <tr> <td><input id="z1" type="number" oninput="calculateSubTotal()"> </td> <td>Shirts - WASH - Qty 1 to 4</td> <td>2.50 ea</td> ...

Utilizing shared data properties in both JavaScript and SCSS within Vue

Vue.js 2 has caught my interest, especially with the single-file component structure: <template> <h1>Hello World</h1> </template> <script> export default { name: 'hello-world', }; </script> <style s ...

Firefox not rendering responsive YouTube embed properly

This method of embedding seems to be functioning well on all browsers except for Firefox; I took advantage of a free trial at crossbrowsertesting.com to verify. I’m not using a direct iFrame embed, and all the solutions I’ve come across are related to ...

Css for tooltips positioned to the left and right

I have recently developed a react component tooltip that is designed to appear based on the direction (top, bottom, left, right) specified in the component parameters. Interestingly, when top or bottom is selected, the tooltip functions perfectly. However, ...

Ways to delete the title from a box in orgChart

Is there a way to remove the title from the box and only show the content? I've searched extensively but haven't found a solution yet. I'm currently using orgChart: https://github.com/dabeng/OrgChart For example, the general manager box s ...

Fetching data dynamically using ajax as you scroll

Currently, I am using the jQuery Tools Plugin to create an image slider. However, I am facing a challenge with loading a large number of images all at once. Since the slider is coded in JavaScript, I am not sure how to control the scroll position. I would ...

How to bring in images from the assets folder using React and Typescript

I'm facing an issue where direct image importing is working, but when using object types, it's not functioning properly. Why could this be happening? I am currently working with "react": "^16.12.0" and "typescript": "~3.7.2" // ./src/assets/baby ...

When browserify is utilized, the error "function is not defined" may show up as an Un

Exploring an example at and attempting a function call as shown below: My HTML code is: <!DOCTYPE html> <html> <head> <title>Testing Browserify</title> <script src="bundle.js"></script> </head> <body& ...

Cycle through matching elements for managing unique slick carousels

My experience with using slick carousel and custom pagination has been positive so far. However, I'm now faced with the challenge of incorporating multiple carousels on a single page. While I have come across solutions, implementing them alongside my ...

SQL inputs with information that updates automatically / autofill SQL input boxes

Is it feasible to create a webpage that can connect to an SQL database, retrieve information from a table, and display it in a text box based on the input provided in another text box? Essentially, I am looking for a way to enable autofill functionality. I ...

Animating the 'body' element using jQuery has no effect

One interesting feature of my site is that when you click on a certain button in the navigation bar, a small grey tab drops down from the top to provide information about the site. The code I used for this animation is as follows: var aboutMenu = function ...

Create a universal formatter for pairs of property names and values that can be applied to any property

Imagine we have an object definition as follows: type Obj = { i: number b: boolean s: string } We want to create a type that allows us to pass a property name and a callback function that expects an argument of the same type as the specified p ...

Guide on retrieving specific values within an array and mapping them to separate arrays using the HttpClient service in Angular 7+

I'm having a tough time grasping the concept of handling data once it's returned from an Http Request in Angular 7+ The Service responsible for fetching each location is shown below: import { Injectable } from '@angular/core'; import ...

Updating dropdown value from a different dropdown selection in Angular 17

I need to set up the form so that selecting Mr in the first dropdown will change the value to male in the second dropdown. Similarly, if Miss/Mrs is selected, the 2nd dropdown should switch to female. Any suggestions on how I can make this work? Here&apo ...

Return all HTML code from the Ajax element

I can't seem to pinpoint the issue with my code. When I make an ajax call using the code below: ajax.js: function ajaxObj(meth, url){ var x = new XMLHttpRequest(); x.open(meth, url, true); x.setRequestHeader("Content-type", "application/x-www_form-u ...

Convert an array of image objects into a video file

My task involves taking an array filled with image objects and encoding it into a movie project. While I have a Java server available for use if necessary, my preference is to handle this client-side using JavaScript. ...

Is there a way to utilize a JavaScript function to transfer several chosen values from a select listbox to a different listbox when a button is clicked?

Is it possible to create a functionality where users can select multiple values from a first list and by clicking a button, those selected values are added to a second list? How can this be achieved through JavaScript? function Add() { //function here ...

Utilizing StyleFunctionProps within JavaScript for Chakra UI Enhancements

I need help figuring out how to implement StyleFunctionProps in my Chakra UI theme for my NextJS project. The documentation on Chakra's website provides an example in Typescript, but I am working with Javascript. Can someone guide me on adapting this ...

Only individual ants are allowed to upload a list item

I'm currently utilizing ant design to facilitate the uploading of a CSV file through this specific form input: ce(Form.Item, { className: 'form_input' }, ce(Upload, { onChange: handleFileChange, className:'csv', multiple: ...