属性“名称”在类型“ {}”上不存在-Angular

时间:2018-09-25 03:49:11

标签: javascript angular typescript

我已经检查过,并且该键确实存在该属性,但是它返回错误name is not a property of {}。我试图将此对象分配给具有其属性的接口,但是它也说我不能为它分配{}。这可能是什么问题?

这是无效的代码 this.companiesArray[0].employees[0].name返回错误name is not a property of {}

这是我正在使用的示例数据,是一组对象(公司)

[
{
"employees": [
  {
    "name": "Amy",
    "gender": "female",
    "level": "2"
  },
  {
    "name": "Chris",
    "gender": "male",
    "level": "4"
  }
  ],
"company": "XYZ",
"tower": "Tower 2"
 },
 {
"employees": [
  {
    "name": "Ben",
    "gender": "male",
    "level": "1"
  },
  {
    "name": "Sarah",
    "gender": "female",
    "level": "1"
  }
  ],
"company": "ABC",
"tower": "Tower 3"
 }
 ]

这里是Angular代码和公司界面

 companiesArray: Company[]
  ngOnInit() {
    this.companyService.obsCompanies.subscribe(companies => {
      this.companiesArray = companies;
      console.log(this.companiesArray[0].employees[0].name);// for testing
    });
	...
  }

export interface Company {
    employees: {}[],
    company: string,
    tower: string
}

2 个答案:

答案 0 :(得分:2)

创建员工界面

export interface Employee {
    name: string;
    gender: string;
    level: string;
}

并将公司更改为

export interface Company {
    employees: Employee[],
    company: string,
    tower: string
}

答案 1 :(得分:0)

当您使用通用签名调用函数时,如果未为函数调用指定类型,并且编译器无法推断该类型,则推断出{}类型,这是编译器错误。

您需要在函数调用中定义类型,以便编译器知道该类型。类似于yourService.get (而不是yourService.get(