Reputation: 243
I'm following the Angular tutorial located on https://angular.io/start. I got all the way through it and am trying to practice building for production locally, but when I build I get this error:
error TS2345: Argument of type 'any' is not assignable to parameter of type 'never'. this.items.push(product);
The 'product' being pushed to the items array is defined as such in the tutorial (in its own separate file, 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: ''
}
];
Here is the file where I'm attempting 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've tried defining the items array in these ways, but all resulted in some error:
items = []
items : any[] = [];
items : {id: bigint, name: string, price: bigint, description, string}[] = [];
Any suggestions would be much appreciated.
Upvotes: 1
Views: 4973
Reputation: 876
(I can't comment) could you expand the example and give the use case? This seems to work:
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)
Upvotes: 0
Reputation: 166
It would be useful is you could provide more code samples (where the item
is coming from) but I think if you are working with an array of objects you should declare an object interface. In Typescript you can't really do it like this
items : {id: bigint, name: string, price: bigint, description, string}[] = [];
For objects you should declare an interface
const product = {
id: 2,
name: 'essa',
price: 700,
description: ''
}
interface Item {
id: number;
name: string;
price: number;
description: string;
}
// Array of objects that have the structure of Item
const items: Item[] = [];
items.push(product);
You also need to make sure that the products
array have the type set to Item[]
as well.
Upvotes: 2