#How to type reduce function correctly?

10 messages · Page 1 of 1 (latest)

amber depot
#

Hello I have this reduce function in project I am currently working on and I can't figure out how to type it properly.

I am just trying to get price of all products in cart.

const totalPrice: number = carted.reduce(acc: number, product: CartedProductType) => (acc += product.price * product.quantity), 0); 

and I am geting this error.

Argument of type '(acc: number, product: CartedProductType) => number' is not assignable to parameter of type '(previousValue: never, currentValue: never, currentIndex: number, array: never[]) => never'.
  Type 'number' is not assignable to type 'never'

I am fairly new to typescript and coding overall but I have tried to google out the problem but nothing worked for me so far.

Thank you for help

grave skiff
#

How is that defined?

amber depot
#
type CartContextType = {
  carted: CartedProductType[] | [];
  setCarted: React.Dispatch<React.SetStateAction<CartedProductType[] | []>>;
};
#

So I have this to set up context but I maybe I forgot to type it when I created state?

#
 const [carted, setCarted] = useState<CartedProductType[] | []>([])
#

Didn't solve the error

grave skiff
#

You should drop the | [].

#

You don't need to represent the possibility of the array being empty in the type system, and [] is an empty tuple type that throws things off.

amber depot
#

ohhh I see, thank you so much that solved the error!