如何制作适用于 angular2fire 可观察响应的打字稿定义?

How to make typescript definitions that work with angular2fire observable responses?

我正在使用 angularfire2 在 Firebase 上构建 Angular2 应用程序。

从实时数据库返回的项目上有额外的字段(例如 $key、$exists),可以在您的应用程序中使用。但是,如果您不在模型定义中包含这些键,typescript 会抛出错误。

例如,假设我有一个名为 item:

的 class
export class Item {
  name: string,
  price: number,
  isOnSale: boolean
}

当该项目通过 angularfire2 返回时,它有额外的 firebase 字段(例如 $key、$exists 等),我有时想访问这些字段:

constructor(private af: AngularFire){
  this.af.database.list('items').subscribe(items => {
    items.forEach(item => this.doSomethingWithDbItem(item));
  })
}

doSomethingWithDbItemAndThenUpdate(item: Item){
  // Now, if I want to access the $key field, I get a typescript error because
  // $key does not exist on my class definition

  if( item.name === 'toy_truck'){
    const key = item.$key; // Will throw error typescript compile error
    this.af.database.object(`items/${key}`).set({isOnSale: true})
  }
}

是否有处理此问题的最佳做法?我可以将数据库键直接添加到模型中。或者创建一个 FB class,它有 $key、$exists 等,然后让我的项目 class 和其他 classes 扩展 FB?

这是一个人为的例子,所以代码可能不完全正确,但希望我的 point/question 是清楚的。

这段代码中的items

this.af.database.list('items').subscribe(items => {
  items.forEach(item => this.doSomethingWithDbItem(item));
})

将是 Object 个实例的数组。它不会是 Item 个实例的数组。也就是说,item instanceof Item 将是 false

因此,告诉 TypeScript 它们就是这样没有多大意义。

相反,您应该使用接口来描述模型的形状。如果你要使用接口,使用具有 AngularFire2 属性的基本接口是微不足道的:

export interface AngularFireObject {
  $exists: () => boolean;
  $key: string;
  $value?: any;
}

export interface Item extends AngularFireObject {
  name: string;
  price: number;
  isOnSale: boolean;
}