When I try to extract an object from the response I get an error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'.
No index signature with a parameter of type 'string' was found on type '{}'.
\\ product.service.ts:
getProducts() {
return this.http.get(this.url)
.pipe(
map(this.listProduct)
);
}
listProduct (prod: object) {
let products : Product[] = [];
if ( prod !== null ) {
Object.keys(prod).forEach( key => {
let product: Product = prod[key]; // an error appears here
product.id = key;
products.push(product);
})
}
return products;
}
maybe the reason is "id?" but that was the only solution that worked
\\ product.modelo.ts:
export class Product {
id?: string;
name!: string;
quantity!: number;
description!: string;
}
CodePudding user response:
It is complaining about the type of prod because it doesn't know it. Try this
let product: Product = (<any>prod).key;
CodePudding user response:
for (let [key, object] of Object.entries(prod)){
let product: Product = object as Product;
product.id = key;
products.push(product)
}
CodePudding user response:
You should set prod paramert to { [key: string]: Product; }
type. You can alson create new type and referece it.
type ProdObjects = {
[key: string]: Product;
};
function listProduct (prod: ProdObjects) {
...
All other hacks are bad practice