查找功能中的类型“从不”不存在属性“ id”

时间:2018-11-24 07:48:26

标签: javascript angular typescript

我正在使用angular并有级联选择

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'上不存在。”

有什么想法吗?预先感谢

2 个答案:

答案 0 :(得分:2)

您从编译器收到的错误是由于selectedAreas声明不正确。通过执行property: [],您可以定义一个只能容纳一个空数组的属性。

使用以下内容代替,它设置默认值(与类型相对):

selectedAreas = [];  // note the equal sign

或更妙的是:

selectedAreas: Area[] = [];

其中Area是您定义其属性的类。

您的其他属性也有同样的问题(property: {}定义了只能是空对象的属性)。

答案 1 :(得分:0)

在Jeto的答案上方添加:

您可能希望在element方法的回调中将any的类型指定为find,以避免任何编译错误:

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>

以下是 Sample StackBlitz 供您参考

相关问题