tengo este codigo:
totalPrice = Object.entries( buyTicketData.pricingAndInvoicingType == PricingAndInvoicingType.invoiceItems ? buyTicketData.invoiceItems : buyTicketData.pricingOptions[startPaymentIn?.pricingOptionId] .invoiceItems ).reduce((newObj, [key, val]) => { (cumulativValue, ii) => { const ret = cumulativValue + (val.quantity ?? startPaymentIn?.invoiceItems[key] ?? 0) * parseInt(val.unitPrice); return ret; }; }, 0); Según tengo entendido preiousValue es un valor acumulativo, y podría ser de tipo diferente con currentValue . En mi caso, el valor previousValue es un número, mientras que current value is an array with a clave and campos de valor.
Pero no funciona, algo funciona, tal vez todo el enfoque sea incorrecto. ¿Qué piensas?
./pages/hu/buyTicket/[eventId].tsx:75:5 Type error: Type '[string, InvoiceItemData]' is not assignable to type 'string'. 73 | startPaymentIn?.pricingOptionId) 74 | ) { > 75 | totalPrice = Object.entries( | ^ 76 | buyTicketData.pricingAndInvoicingType == 77 | PricingAndInvoicingType.invoiceItems 78 | ? buyTicketData.invoiceItems error Command failed with exit code 1.Object.entries convierte un objeto en una lista de pares clave-valor.
Por ejemplo:
let invoiceItems = { 'key-1': 100, 'key-2': 200, }; Object.entries(invoiceItems); // [['key-1', 100], ['key-2', 200]]Si ahora desea reducir esta lista, los dos primeros argumentos de la función de devolución de llamada de reducción serán:
un acumulador (si quieres calcular la suma de algo, será un number )
cada elemento de la lista, en mi ejemplo son de tipo [string, number]
Para construir sobre mi ejemplo, podría sumar todos los valores juntos:
let totalPrice = Object.entries(invoiceItems).reduce( (cumulativeValue, [key, val]) => { // in my case, key is a string and val is of type number return cumulativeValue + val; }, 0 // the initial value ); // totalPrice === 300Espero que esto explique un poco cómo se forman los tipos. Para responder a su pregunta, creo que su reductor está un poco desordenado ya que tiene 2 funciones. Para solucionarlo, esto debería funcionar:
.reduce( (cumulativeValue, [key, val]) => { const ret = cumulativeValue + (val.quantity ?? startPaymentIn?.invoiceItems[key] ?? 0) * parseInt(val.unitPrice); return ret; }, 0 );Creo que no estás devolviendo nada dentro de la función de reducción. La función de reducción necesita un valor devuelto, y ese valor devuelto se pasa a anteriorValue en la siguiente iteración. Por lo tanto, es acumulativo en este punto porque manipula y devuelve datos, úselo como el valor anterior de la siguiente iteración. Así que trata de devolver algo dentro de él. Además, creo que está utilizando mecanografiado, por lo que le recomiendo que inserte algunas definiciones de tipo en la función de reducción.
Finalmente descubrí que, en lugar de reduce , necesito un bucle for simple.