"Creating a Typescript array by extracting items from a different const array (as seen in the official beginner tutorial

Currently, I am working through the Angular tutorial that can be found at https://angular.io/start. After successfully completing the tutorial, I decided to practice building for production locally. However, when attempting to build, I encountered this error:

error TS2345: Argument of type 'any' is not assignable to parameter of type 'never'. this.items.push(product);

The object 'product' that is being added to the items array is defined as follows in the tutorial (in a separate file named products.ts):

export const products = [ 
  {
    id: 1,
    name: 'Phone XL',
    price: 799,
    description: 'A large phone with one of the best screens'
  },  
  {
    id: 2,
    name: 'Phone Mini',
    price: 699,
    description: 'A great phone with one of the best cameras'
  },  
  {
    id: 3,
    name: 'Phone Standard',
    price: 299,
    description: ''
  }
];

Below is part of the code where I am trying to use it:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

import { products } from './products';

@Injectable()

export class CartService {
  items = []; 

  constructor(
    private http: HttpClient
  ) {}

  addToCart(product) {
    this.items.push(product);
  }

  getItems() {
    return this.items;
  }

  clearCart() {
    this.items = []; 
    return this.items;
  }

  getShippingPrices() {
    return this.http.get('/assets/shipping.json');
  }
}

I have attempted to define the items array in multiple ways, all resulting in errors:

items = []

items : any[] = [];

items : {id: bigint, name: string, price: bigint, description, string}[]  = [];

If you have any suggestions or solutions, your input would be greatly appreciated.

Answer №1

To enhance clarity, it would be beneficial if additional code samples were provided to show where the item is sourced from. When working with an array of objects in Typescript, it is advisable to declare an object interface like so:

items : {id: bigint, name: string, price: bigint, description, string}[]  = [];

When dealing with objects, the use of an interface is recommended:

const product = {
  id: 2,
  name: 'essa',
  price: 700,
  description: ''
}

interface Item {
  id: number;
  name: string;
  price: number;
  description: string;
}

// Array of objects that follow the structure defined in Item
const items: Item[] = [];

items.push(product);

Furthermore, it's essential to ensure that the products array also has its type set to Item[].

Answer №2

I would like to understand the example better, could you provide a use case along with an expanded explanation? Here is a snippet that appears to be functional:

export const products = [ 
  {
    id: 1,
    name: 'Phone XL',
    price: 799,
    description: 'A large phone with one of the best screens'
  },  
  {
    id: 2,
    name: 'Phone Mini',
    price: 699,
    description: 'A great phone with one of the best cameras'
  },  
  {
    id: 3,
    name: 'Phone Standard',
    price: 299,
    description: ''
  }
];

const items = [];

this.items.push(products)

console.log(items)

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

Angular: Navigating to a distinct page based on an API response

In order to determine which page to go to, based on the response from an API endpoint, I need to implement a logic. The current API response includes an integer (id) and a string (name). Example Response: int: id name: string After making the API call, I ...

Extracting an array from an HTTP response in Angular/Typescript using the map operator or retrieving a specific element

Q1: How can I extract an array of objects from a http response using map in Angular? Q2: Is there a way to retrieve a specific object from a http response by utilizing map in Angular? Below are the example URL, sample data, CurrencyAPIResponse, and Curre ...

Configuration object for Webpack is not valid

I encountered an error while using webpack that says: Invalid configuration object. Webpack has been initialized with a configuration object that does not conform to the API schema. - configuration.resolve has an unknown property 'extension&ap ...

Enhancing the default functionality of React.FC within Next.js

Currently, I am working on a tutorial in Nextjs that employs the code snippet below in JavaScript. However, I am planning to transition it to TypeScript. Since I am relatively new to TypeScript, I have attempted various solutions from different sources but ...

Spring OAuth2 preflight responds with a 302 status code

I have implemented OAuth2 in my Spring application with a resource server and authentication server. I am attempting to send a GET request to the resource server from Angular2, but I am receiving a 302 response for the OPTIONS request. Unfortunately, I do ...

Angular 10 carousel malfunction: unable to scroll images as intended

Recently, I attempted to integrate a bootstrap carousel into my angular web page. I copied the source code directly from the bootstrap site, so I assumed everything was configured correctly... Despite this, the carousel does not slide as expected. Additio ...

When attempting to compile Typescript code, error TS1128 occurs indicating a missing declaration or statement. However, the code functions correctly when executed through a server

Currently, I'm in the process of developing a project using Angular2. As part of this project, I have created a primary Component class which serves as a central piece: import { Component, OnInit} from '@angular/core'; import { submitServi ...

When hovering over various div elements in HTML

I've been experimenting with some code lately, and I'm trying to change the text color of a menu element when hovering over it. I can alter the background color just fine, but for some reason, the text color remains unchanged. Can anyone offer a ...

The marriage of Vue 2.0 and Rails 5: Shifting from Reactive to Declarative Rendering

As I make my way through the Vue guide with a Rails 5 app, I've noticed that although I am able to update my Vue js object, the DOM doesn't behave as described in the Declarative Rendering section. The data and the DOM are supposed to be linke ...

When dynamically loaded HTML is involved, Javascript ajax calls often fail to execute properly

Currently, I am in the process of creating a JavaScript script that can facilitate clicking through <a href> links by only replacing the inner HTML instead of reloading the entire page. The interesting thing is, it seems to be functioning properly, e ...

What is the process for adding color to an Object3D Object in ThreeJs?

My project involves importing Objects from a file, and I want to be able to color them by clicking on them. After attempting the following code: let mat = (this.scene.children[4].getObjectByName(intersects[0].object.name) as THREE.Mesh).material.color.set ...

Issue encountered during rendering: The function used is not a filter

Everything works fine with the search filter and pagination on the initial load. However, upon clicking to go to the next page, an error occurs stating **'Error in render: "TypeError: this.tickets.filter is not a function"'**. This issue can b ...

Having trouble understanding why ng-resource refuses to return an array

I've recently encountered an issue while using AngularJS and NGResource. For some reason, every time I try to use the query function, I receive an empty array in return. Within my controller, the code looks like this: Task = $resource('/tasks&a ...

Issue with Vue JS: e.preventDefault not functioning correctly when using Axios

I am facing an issue in my Laravel project where I have implemented a method in the Vue instance to validate resource availability upon form submission. The validation is done through an AJAX call using axios, and if any resources are unavailable, I receiv ...

Unable to integrate any modules or components from bit.dev into my React application

I am currently working on a React project and encountering an issue with importing a component from bit.dev. After installing the package via my terminal with the command: bit import nexxtway.react-rainbow/button You can find more information about it t ...

Encountering TypeScript error in the beforeRouteUpdate hook with Vue and vue-property-decorator

I am developing an application using Vue 2 with TypeScript and vue-property-decorator. Within my component, I am utilizing the beforeRouteEnter/beforeRouteUpdate hooks. One of the methods in my component is findProjects, which I want to call within the bef ...

Steps to resolve the error message "The port 9876 has no listening server when karma is running"

I have a situation where I am executing the following code: PS D:\app> karma run However, an error is being displayed: [2013-11-29 17:39:54.297] [DEBUG] config - Loading config D:\app\karma.conf.js There is no server listening on port ...

Tips for changing the visibility of a div within table rows upon clicking

Struggling to solve this jQuery issue with a table that displays numbers on each row. I want to be able to click on one of the numbers, which is a href link, and toggle only the corresponding div called "test" instead of toggling all rows at once. How can ...

Pass values between functions in Typescript

Currently, I have been working on a project using both Node JS and Typescript, where my main challenge lies in sharing variables between different classes within the same file. The class from which I need to access the max variable is: export class co ...

What could be the reason for not receiving any response from my Firestore query?

Hey there! I'm delving into the world of Firebase for the first time and just set up the Firestore emulator. I've added some data that I want to fetch in my Nextjs app. Once I initialized firebase, this is what my component code looks like: funct ...