简体   繁体   中英

Property 'id' does not exist on type 'never' in find function

I am working with angular and have cascading selects

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'];
}

In the function onSelectArea I am getting an error on element.id

"[ts] Property 'id' does not exist on type 'never'."

Any ideas? Thanks in advance

That error you're getting from the compiler is due to selectedAreas not being declared properly. By doing property: [] you define a property that can only hold an empty array.

Use the following instead, which sets the default value (as opposed to the type):

selectedAreas = [];  // note the equal sign

Or better yet:

selectedAreas: Area[] = [];

where Area would be a class where you define its properties.

You also have the same issue for your other properties ( property: {} defines a property that can only be an empty object).

Adding on the top of Jeto's answer:

You might want to specify the types of element as any in the callbacks to the find method to avoid any compilation errors:

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'];
  }
}

And in your Template:

<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>

Here's a Sample StackBlitz for your ref

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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