Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

185
Vistas
Typescript and Array.map with thisArg results in an error

In Javascript, I can pass a thisArg into the Array.map function as a second argument. Here is a minimal example.

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

The result is the array [1, 3, 6, 10, 15, 21]. When I try the same in Typescript, I get the following error.

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

How can I annotate the code so that this inside the callback has the correct type?

I have tried giving everything a type annotation like this,

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);

But this doesn't get rid of the error because none of these annotations specifies the type of this explicitly.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can override the this parameter of your mapping function with your type:

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

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

PS: Very similar questions have been asked on SO already.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda