简体   繁体   English

Angular2和Typescript-类型上不存在属性名称

[英]Angular2 & Typescript - Property name does not exist on type

The suggested answer to this question using find does not work in Typescript, it cannot compile. 使用find 对此问题的建议答案在Typescript中不起作用,无法编译。 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: 这是Category对象:

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'): 我试图找到这样的(值是一个字符串,例如“ Wood”):

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

It says Property name does not exist on type 'Category'. 它说类型“类别”上不存在属性名称。

That is because your class Category does not have any properties. 这是因为您的类Category没有任何属性。 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. 现在, Category所有参数也是其公共属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM