Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

186
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda