Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

forEach Typescript TS2339 "does not exist on type 'void'"

Tags:

typescript

Trying to find the intersection of two arrays, why am I getting TS2339:Property 'collection' does not exist on type 'void'?

All arrays are declared in the same class.

this.locations.forEach(function(location) {
    this.collection.locations.forEach(function(id) {
        if(location._id === id) {
            this.display.push(location);
        }
    });
});
like image 789
Jeffrey Haskell Avatar asked Dec 23 '22 15:12

Jeffrey Haskell


1 Answers

Using a function takes the this from the caller (something in forEach in your case); using => takes the this from the outer scope. Thus use:

this.locations.forEach(location => {
    this.collection.locations.forEach(id => {
        if(location._id === id) {
            this.display.push(location);
        }
    });
});

I recommend the following readings:

  • A Refresher on this
  • Arrow Functions
like image 76
ideaboxer Avatar answered Jan 21 '23 03:01

ideaboxer