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

184
Views
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 answers
Answer question

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 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!