Javascript 查找函数中的类型“从不”上不存在属性“id”
我正在使用angular和级联选择Javascript 查找函数中的类型“从不”上不存在属性“id”,javascript,angular,typescript,Javascript,Angular,Typescript,我正在使用angular和级联选择 city: {}; area: {}; selectedAreas: []; selectedSuburbs: []; arrAddress = [{ city: "Auckland", id: 1, areas: [{ area: "Waitakere", id: 11, suburbs: [{ suburb: "Rodney", id: 12 }, {
city: {};
area: {};
selectedAreas: [];
selectedSuburbs: [];
arrAddress = [{
city: "Auckland",
id: 1,
areas: [{
area: "Waitakere",
id: 11,
suburbs: [{
suburb: "Rodney",
id: 12
},
{
suburb: "North Shore",
id: 13
},
{
suburb: "City",
id: 14
},
]
}]
}];
onSelectCity(e) {
this.city = this.arrAddress.find(element => element.id === Number(e.value));
this.selectedAreas = this.city['areas'];
}
onSelectArea(e) {
this.area = this.selectedAreas.find(element => element.id === Number(e.value));
this.selectedSuburbs = this.area['suburbs'];
}
在函数onSelectArea中,我在element.id上得到一个错误
[ts]属性“id”在类型“never”上不存在
有什么想法吗?提前感谢您从编译器中得到的错误是由于所选区域未正确声明所致。通过执行属性:[]可以定义一个只能容纳空数组的属性 改为使用以下选项,设置与类型相反的默认值:
selectedAreas = []; // note the equal sign
或者更好:
selectedAreas: Area[] = [];
where Area将是定义其属性的类
您的其他属性属性也有同样的问题:{}定义了一个只能是空对象的属性。在Jeto的答案顶部添加: 您可能希望在find方法的回调中将元素的类型指定为any,以避免任何编译错误:
import { Component } from '@angular/core';
@Component({...})
export class AppComponent {
city = {};
area = {};
selectedAreas: any[] = [];
selectedSuburbs: any[] = [];
arrAddress = [...];
onSelectCity(e) {
this.city = this.arrAddress.find((element: any) => element.id === Number(e.value));
this.selectedAreas = this.city['areas'];
}
onSelectArea(e) {
this.area = this.selectedAreas.find((element: any) => element.id === Number(e.value));
this.selectedSuburbs = this.area['suburbs'];
}
}
在模板中:
<select (change)="onSelectCity($event.target)">
<option value="null">Select a City</option>
<option *ngFor="let city of arrAddress" [value]="city.id">{{ city.city }}</option>
</select>
<br><br>
<select (change)="onSelectArea($event.target)" [disabled]="!selectedAreas">
<option value="null">Select an Area</option>
<option *ngFor="let area of selectedAreas" [value]="area.id">{{ area.area }}</option>
</select>
这里有一个供参考的示例请添加一些示例数据。