Type 'Observable<DocumentData[]>' is not assignable

Viewed 447

I'm new to angular and to firebase and I try to do a simple program using the example of the angular/fire library:

import { Component } from '@angular/core';
import { Firestore, collectionData, collection } from '@angular/fire/firestore';
import { Observable } from 'rxjs';

interface Item {
  name: string
};

@Component({
  selector: 'app-root',
  template: `
  <ul>
    <li *ngFor="let item of item$ | async">
      {{ item.name }}
    </li>
  </ul>
  `
})
export class AppComponent {
  title = 'firetest2812';
  item$: Observable<Item[]>;
  constructor(firestore: Firestore) {
    const collect = collection(firestore, 'items');
    this.item$ = collectionData(collect);
  }
}

While compiling I got these error: " Error: src/app/app.component.ts:24:5 - error TS2322: Type 'Observable<DocumentData[]>' is not assignable to type 'Observable<Item[]>'. "

Can someone tell me what's wrong please? Thanks!

3 Answers

I solved this by casting like this :

 this.item$ = collectionData(collect) as Observable<Item[]>

You have to pass your interface as type to the collection function.

 const collect = collection<Item>(firestore, 'items');

You need to provide the generic type in the collectionData() function since you specified the item$ Observable type as Item[] in the property.

export class AppComponent {
  title = 'firetest2812';
  item$: Observable<Item[]>;
  constructor(firestore: Firestore) {
    const collect = collection(firestore, 'items');
    // Specify the type here
    this.item$ = collectionData<Item>(collect);
  }
}

Alternatively, the lazy answer is do use any.

export class AppComponent {
  title = 'firetest2812';
  item$: Observable<any[]>;
  constructor(firestore: Firestore) {
    const collect = collection(firestore, 'items');
    // Specify the type here
    this.item$ = collectionData(collect);
  }
}
Related