簡體   English   中英

數組中的泛型類型?

[英]Generic type in Array?

我試圖創建一個將一些數據顯示為按鈕列表的模型應用程序。 我實現了所有內容,但現在正面臨這個問題。 我初始化了一個數組和另一個數據類。

-items.ts

  export class ItemPage {

  items: Item[] = [];

  constructor() {

    this.items.push(
      new Item(1, 'Apple', 'Green', 6, true));
    this.items.push(
      new Item(2, 'Banana', 'Yellow', 15, false));
  }

數據類看起來像這樣

-item.ts

export class Item {
  constructor(
    id: number,
    fruit: string,
    color: string,
    quantity: number,
    onStock: boolean,
  ) { }
}

我遇到商品問題items: Item[] = []; 當我運行ionic serve 它說Generic type 'Item' requires 2 type argument(s)並且type Item<K extends string, T> = { [P in K]: T; } Construct a type with a set of properties K of type T type Item<K extends string, T> = { [P in K]: T; } Construct a type with a set of properties K of type T
我試圖解決它,但是沒有幫助,有人知道如何解決這個問題嗎?

謝謝

我沒有完全設法重現問題,而是以兩個空對象結束。 錯誤似乎是您沒有將類中的屬性設置為public ,因此將類更改為:

export class Item {
  constructor(
    public id: number,
    public fruit: string,
    public color: string,
    public quantity: number,
    public onStock: boolean,
  ) { }
}

似乎工作正常: Plunker

但是 ,如果您不需要類中的函數或其他原因,我強烈建議您改用接口。 所以我想說你做界面:

export interface Item {
  id: number;
  fruit: string;
  color: string;
  quantity: number;
  onStock: boolean;
}

constructor(private navController: NavController) {
  this.items.push({id:1, fruit:'Apple', color:'Green', quantity:6, onStock:true});
  this.items.push({id:2, fruit: 'Banana',color:'Yellow',quantity:15,onStock:false})
}

希望這會有所幫助!

暫無
暫無

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

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