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