Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

302
Views
¿Es posible tener un tipo diferente para el valor anterior y el valor actual?

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.
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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:

  1. un acumulador (si quieres calcular la suma de algo, será un number )

  2. 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 === 300

Espero 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 );
about 4 years ago · Juan Pablo Isaza Report

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.

about 4 years ago · Juan Pablo Isaza Report

0

Finalmente descubrí que, en lugar de reduce , necesito un bucle for simple.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!