1

The suggested answer to this question using find does not work in Typescript, it cannot compile. I've looked at other similar questions, but they all seem a little different (context) in some way.

This is the array:

categories: Category[] = [];

This is Category object:

export class Category{
  constructor(
    id: string,
    name: string,
    category_types: Object[]
  ) {}
}

and I am trying to find like this (value is a string, eg 'Wood'):

let a = this.categories.find(v => v.name === value);

It says Property name does not exist on type 'Category'.

Community
  • 1
  • 1
rmcsharry
  • 5,363
  • 6
  • 65
  • 108

1 Answers1

4

That is because your class Category does not have any properties. You can define parameter properties to create properties directly out of constructor parameters:

export class Category{
  constructor(
    public id: string,
    public name: string,
    public category_types: Object[]
  ) {}
}

Now all the parameters of Category are also its public properties.

Saravana
  • 37,852
  • 18
  • 100
  • 108