首页 > 解决方案 > Typescript 错误类型“ArrayBuffer”不可分配给类型“Item []”

问题描述

在我的 ionic 项目中,我想从 postgreSql 数据库的表中获取行,然后将这些行分配给 item[]: currentItems。

我检查了 postgreSql 的返回行,格式如下:

[
 anonymous 
 {
   name: jack,
   email: jack@gmail.com
 }
 anonymous 
 {
   name: mark,
   email: mark@gmail.com
 }
]

但是,当我将它分配给 item[]: currentItems 时,我收到错误消息: Typescript 错误类型“ArrayBuffer”不可分配给类型“Item[]”。

以下是我的 inoic 代码的一部分:

项目.ts:

export class Item {

  constructor(fields: any) {
    // Quick and dirty extend/assign fields to this model
    for (const f in fields) {
      // @ts-ignore
      this[f] = fields[f];
    }
  }

}

列表master.ts:

export class ListMasterPage {
  currentItems: Item[];

  params: { uid: string } = {
    uid: "test"
  };

  constructor(public navCtrl: NavController,
    public items: Items,
    public modalCtrl: ModalController,
    public globalvar: GlobalvarProvider,
    public toastCtrl: ToastController) {

    this.params.uid = this.globalvar.userIdentifier
    this.items.query(this.params).subscribe((resp) => {
    /* here assign the received rows from database to the currentItems */
      this.currentItems = resp;
    }, (err) => {
    });;
  }

物品.ts

export class Items {

  constructor(public api: Api) { }

  query(params?: any) {
    /* here get the rows from the postgresql database, I have confirmed the data received is in the format mentioned in above question description */
    return this.api.get('getfriends', params);
  }

  add(item: Item) {
  }

  delete(item: Item) {
  }

}

谢谢

标签: typescriptionic3

解决方案


看起来您可能有来自解析 JSON 的有效纯对象。要解决 TypeScript 认为 type 为 的原因ArrayBuffer,我需要查看get方法中调用的Items.prototype.query方法的声明。如果您想要Item对象而不是普通对象,则必须自己实例化它们,例如:

this.currentItems = (<any[]>resp).map((i) => new Item(i));

或使用序列化库。


推荐阅读