Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Im getting an error "Spread types may only be created from object types.ts(2698)"

import { Injectable } from '@angular/core';
import { AngularFirestore } from '@angular/fire/firestore';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class FirestoreDbService {

  constructor(private db: AngularFirestore) { }

  getBuildList() {
    // return this.db.collection('Builds').valueChanges();
    return this.db.collection('Builds').snapshotChanges().pipe(
      map(docArray => {
        return docArray.map(doc => {
          console.log('==', doc.payload.doc.id);
          console.log('$==$', doc.payload.doc.data());
          return{
            id: doc.payload.doc.id,
            ... doc.payload.doc.data()
          }
        })
      })
    )
  }
}

On the last line I am getting the error. I think this is something to do with typescript. Any help appreciated

like image 817
Luke Sweeney Avatar asked Feb 26 '20 19:02

Luke Sweeney


People also ask

How do you fix spread types may only be created from object types?

The "Spread types may only be created from object types" error occurs when we try to use the spread operator with a value that is possibly not an object. To solve the error, use a conditional to make sure the value is an object before using the spread operator.

Can you spread types in TypeScript?

If we are using TypeScript version 4 or beyond, we can spread tuple generic parameter types. This is useful to help TypeScript better infer types on expressions that involve tuples.


1 Answers

Use the as keyword:

... doc.payload.doc.data() as {} 

This will tell the compiler to treat doc.payload.doc.data() as an object.

like image 92
Peter Haddad Avatar answered Nov 16 '22 01:11

Peter Haddad