简体   繁体   English

数组中的泛型类型?

[英]Generic type in Array?

I was trying to create a mockup app that shows some data as a list of buttons. 我试图创建一个将一些数据显示为按钮列表的模型应用程序。 I implemented everything but I'm facing this problem right now. 我实现了所有内容,但现在正面临这个问题。 I initialised an array and another class for the data. 我初始化了一个数组和另一个数据类。

-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));
  }

and the data class looks like this 数据类看起来像这样

-item.ts

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

I'm facing a problem with items: Item[] = []; 我遇到商品问题items: Item[] = []; when I run ionic serve . 当我运行ionic serve It says Generic type 'Item' requires 2 type argument(s) and type Item<K extends string, T> = { [P in K]: T; } Construct a type with a set of properties K of type T 它说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 . type Item<K extends string, T> = { [P in K]: T; } Construct a type with a set of properties K of type T
I tried to solve it but it didn't help, does anyone has any Idea how to solve this? 我试图解决它,但是没有帮助,有人知道如何解决这个问题吗?

Thanks 谢谢

I didn't exactly manage to reproduce the issue, but instead ending up with two empty objects. 我没有完全设法重现问题,而是以两个空对象结束。 The error seems that you are not setting the properties in your class as public , so changing your class to: 错误似乎是您没有将类中的属性设置为public ,因此将类更改为:

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

seemed to work fine: Plunker 似乎工作正常: Plunker

BUT I highly suggest you should use interfaces instead, if you don't need to have functions in classes or some other reason. 但是 ,如果您不需要类中的函数或其他原因,我强烈建议您改用接口。 So I'd say you make interface: 所以我想说你做界面:

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

Hopefully this helps! 希望这会有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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