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

188
Views
Typescript y Array.map con thisArg dan como resultado un error

En Javascript, puedo pasar un thisArg a la función Array.map como segundo argumento. Aquí hay un ejemplo mínimo.

 const a = [1,2,3,4,5,6]; a.map(function(e) { this.sum += e; return this.sum; }, {sum: 0});

El resultado es la matriz [1, 3, 6, 10, 15, 21] . Cuando intento lo mismo en Typescript, aparece el siguiente error.

 'this' implicitly has type 'any' because it does not have a type annotation. ts(2683)

¿Cómo puedo anotar el código para que this dentro de la devolución de llamada tenga el tipo correcto?

He intentado darle a todo una anotación de tipo como esta,

 const a: number[] = [1,2,3,4,5,6]; const S: {sum: number} = {sum: 0}; a.map(function(e: number): number { this.sum += e; return this.sum; }, S);

Pero esto no elimina el error porque ninguna de estas anotaciones especifica explícitamente el tipo de this .

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Puede anular this parámetro de su función de mapeo con su tipo:

 a.map(function(this: {sum: number}, e: number): number { this.sum += e; return this.sum; }, S);

Consulte https://www.typescriptlang.org/docs/handbook/2/functions.html#declaring-this-in-a-function

PD: Ya se han hecho preguntas muy similares en SO .

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!