Answer the question
In order to leave comments, you need to log in
Why is it throwing an error in the function?
I have a couple of functions in which the same errors can not understand why they occur there
error TS2345: Argument of type 'Products | undefined' is not assignable to parameter of type 'Products'. Type 'undefined' is not assignable to type 'Products'.
export type Products = {
id: number,
title: string,
images: string[],
currentImageIndex: number,
isCycleMode: boolean,
cantGoPrev: boolean,
cantGoNext: boolean,
price: number,
company: string,
info: string,
inCart: boolean,
count: number,
total: number
}
getItem = (id: number) => {
return this.state.products.find(item => item.id === id);
};
addToCart = (id: number) => {
let tempProduct: Products[] = [...this.state.products];
//тут ошибка(this.getItem(id))
const index = tempProduct.indexOf(this.getItem(id));
const product = tempProduct[index];
product.inCart = true;
product.count = 1;
const price = product.price;
product.total = price;
this.setState(
() => {
return {
products: tempProduct,
cart: [...this.state.cart, product]
}
}
,
() => {
this.addTotals();
}
);
};
increment = (id: number) => {
let tempCart = [...this.state.cart];
const selectedProduct = tempCart.find(item => item.id === id);
// тут такая же ошибка indexOf(selectedProduct)
const index = tempCart.indexOf(selectedProduct);
const product = tempCart[index];
product.count = product.count + 1;
product.total = product.count * product.price;
this.setState(
() => {
return {
cart: [...tempCart]
};
},
() => {
this.addTotals();
}
);
};
Answer the question
In order to leave comments, you need to log in
Good afternoon.
The getItem method returns either Products or undefined if no product is found. Make a terminal condition and specify strong typing for the used array next.
addToCart = (id: number) => {
let tempProduct: Products[] = [...this.state.products];
const item = this.getItem(id);
if(item === undefined) {
// ... инструкция при возникновении терминального условия, например, ошибка
return;
}
const index = tempProduct.indexOf(item as Products); // строгая типизация для item
// ...
};
getItem = (id: number): Products => {
return this.state.products.find(item => item.id === id);
};
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question