簡體   English   中英

類型“接口”中不存在屬性?

[英]A property does not exist in type “Interface”?

我是Typescript的新手。 我正在嘗試使用接口作為數組類型。 我仍然按順序構造文字對象,盡管仍然出現此錯誤:

輸入'{id:number; title:字符串; 圖片:字符串; 字:字符串; 描述:字符串; } []'不能分配給'IWordList []'類型。
輸入'{id:number; title:字符串; 圖片:字符串; 字:字符串; 描述:字符串; }”不可分配給“ IWordList”類型。 對象文字只能指定已知的屬性,並且'id'在'IWordList'類型中不存在。

請注意,這種情況與“ id”本身無關,但是如果我添加了任何附加屬性,則會出現相同的錯誤

IWordList.ts

export interface IWordList{
    id : number;
    title : string;
    image : string;
    words : string;
    description : string;
}

wordlistsdata.service.ts

import { Injectable } from '@angular/core';
import { IWordList } from './IWordlist';

@Injectable()
export class WordlistsdataService {

  constructor() { }

  private allWordLists : IWordList[] = 
  [
      {
          id : 1,
          title : "Animals",
          image : "/src/app/images/wordlists/animals_background.jpg",
          words : "cat,elephant,cow,duck",
          description : "sdadasd"
      },
      {   
          id : 2,
          title : "Jobs",
          image : "/src/app/images/wordlists/jobs_background.jpg",
          words : "engineer,farmer,artist,programmer",
          description : "sdadasd"
      }

    ]

  public getWordList() : IWordList[]{
    return this.allWordLists;
  }

  public getOneWordList(id : number) : string[] {
    return 
  }
}

我只是將您的代碼復制到Plunker中,所以效果很好。 您可以在這里看到我的代碼: https : //plnkr.co/edit/sxcYl5v5jBlfzZ31fHLd?p=preview

看看是否也可以從那里運行它。

嗯...但是這個工具需要我粘貼代碼...即使您上面有它...所以這里是AppModule:

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App ],
  providers: [ WordlistsdataService ],
  bootstrap: [ App ]
})
export class AppModule {}

我有同樣的錯誤。 它顯示在我的構建手表中,但未顯示在Linter中,后者檢測到這些錯誤。 因此,我決定重新啟動構建,並遇到一個新錯誤,這是指我創建了一個不帶引發錯誤的屬性的對象的情況(在您的情況下為“ id”)。 有趣的是,林特錯過了那個實際的錯誤。 我修復了此代碼,以便定義了“ id”,然后再次開始構建。 這次它沒有任何錯誤。

如果有人偶然發現此錯誤,我最近通過webpack開發服務器和熱模塊重裝獲得了此錯誤。 唯一可行的解​​決方案:

重新啟動webpack開發服務器,以便從頭開始編譯

試試這個:

export interface IWordList{
    id ?: number;
    title : string;
    image : string;
    words : string;
    description : string;
}

? 運算符使您可以將其設置為可選。

暫無
暫無

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

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