簡體   English   中英

打字稿錯誤類型“ArrayBuffer”不可分配給“Item[]”類型

[英]Typescript Error Type 'ArrayBuffer' is not assignable to type 'Item[]'

在我的 ionic 項目中,我想從 postgreSql 數據庫的表中獲取行,然后將行分配給 item[]: currentItems。

我檢查了 postgreSql 的返回行,它的格式為:

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

但是,當我將它分配給 item[]: currentItems 時,我得到的錯誤是: Typescript Error Type 'ArrayBuffer' is notassignable to type '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) => {
    });;
  }

items.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) {
  }

}

謝謝

看起來您可能通過解析 JSON 獲得了有效的普通對象。 要解決 TypeScript 認為類型是ArrayBuffer ,我需要查看在Items.prototype.query方法中調用的get方法的聲明。 如果您想要Item對象而不是普通對象,則必須自己實例化它們,例如:

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

或使用序列化庫。

暫無
暫無

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

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