[英]Property 'name' does not exist on type '{}' - Angular
I have checked and the property does exist with the key but it returns the error name is not a property of {}
. 我已经检查过,该键确实存在该属性,但是它返回的错误name is not a property of {}
。 I tried to assign this object to an interface complete with its properties however it also says I cannot assign {} to it. 我试图将此对象分配给具有其属性的接口,但是它也说我不能为它分配{}。 What could be the problem to this? 这可能是什么问题?
This is the code that doesn't work this.companiesArray[0].employees[0].name
which returns the error name is not a property of {}
. 这是无效的this.companiesArray[0].employees[0].name
代码,它返回错误name is not a property of {}
。
This is the sample data I'm working with, an array of objects (Companies) 这是我正在使用的示例数据,是一组对象(公司)
[ { "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" } ]
Here is the Angular code and the Company Interface 这是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 }
Create an interface Employee 创建一个界面Employee
export interface Employee {
name: string;
gender: string;
level: string;
}
and change Company to 并将公司更改为
export interface Company {
employees: Employee[],
company: string,
tower: string
}
That is a compiler error you get when you call a function with a generic signature and if you do not specify a type to the function call and the compiler cannot infer the type so it infers type {}. 这是当您使用通用签名调用函数并且未为函数调用指定类型并且编译器无法推断该类型从而推断类型{}时遇到的编译器错误。
You need to define the type on the function call so that the compiler knows the type. 您需要在函数调用中定义类型,以便编译器知道该类型。 Something like yourService.get<YourType>( rather than yourService.get( 类似于yourService.get <YourType>(而不是yourService.get(
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.