Typeerror: Cannot read Property 'Concat' of Undefined - Typescript?

Asked

Viewed 1,094 times

1

if (dataFindCategories && dataFindCategories.length !== 0) {
    let dataFindProducts: Product[];
    dataFindCategories.forEach((category) => {          
        dataFindProducts.concat(this.productRepository.findByCategory(category.id));
    });
}

When this foreach runs it returns me this error:

  • Typeerror: Cannot read Property 'Concat' of Undefined

For each category he will do a search for ID that I had returned one Product[], i need to concatenate each return into a variable, in case the dataFindProducts

  • that return what: productRepository.findByCategory

2 answers

2


You’re declaring the variable, but you’re not initiating it, so yours dataFindProducts is equal to undefined, try initializing it with an empty array

let dataFindProducts: Product[] = [];
  • Thank you was right!

1

Since you are using the superset use the type Array (which is the Generic type) as follows, minimal example:

class Produto {
    constructor(public id: number){    
    }
} 

class Category {
    constructor(public id: number){    
    }
}

const dataFindCategories = Array<Category>();
dataFindCategories.push(new Category(1));
dataFindCategories.push(new Category(2));
dataFindCategories.push(new Category(3));

let dataFindProducts = Array<Produto>();
dataFindCategories.forEach((category: Category) => {
    dataFindProducts = 
        dataFindProducts.concat(category.id);
});

console.log(dataFindProducts);

and pay attention that when using .concat the last change must be returned to the variable, because .concat returns another array.

Another way is with Spread Operator:

class Produto {
    constructor(public id: number){
    }
} 

class Category {
    constructor(public id: number){
    }
}

const dataFindCategories = [];
dataFindCategories.push(new Category(1));
dataFindCategories.push(new Category(2));
dataFindCategories.push(new Category(3));
dataFindCategories.push(new Category(4));

let dataFindProducts = [];
dataFindCategories.forEach((category: Category) => {
    dataFindProducts = [... dataFindProducts, category.id]; // Spread
});
console.log(dataFindProducts);
  • 1

    Got it! Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.