簡體   English   中英

查找功能中的類型“從不”不存在屬性“ id”

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

我正在使用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'上不存在。”

有任何想法嗎? 提前致謝

您從編譯器收到的錯誤是由於selectedAreas聲明不正確造成的。 通過執行property: []您可以定義只能容納一個空數組的屬性。

請改用以下命令,它設置默認值(與類型相反):

selectedAreas = [];  // note the equal sign

或者更好:

selectedAreas: Area[] = [];

其中Area是您定義其屬性的類。

您的其他屬性也有同樣的問題( property: {}定義了只能是空對象的屬性)。

在Jeto的答案之上添加:

您可能希望在find方法的回調中將element的類型指定為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>

這是供您參考的示例StackBlitz

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM