FireBase won’t save TypeScript object: an object

Google FireBase doesn’t want your type information, you’d be forgiven for not knowing this from the error message you got when trying to upload a typed object:

ERROR FirebaseError: Function CollectionReference.add() requires its first argument to be of type object, but it was: an object

FireBase wants an object and you gave it an object! What this message is really saying it that it wants is a plain, un-typed object and you gave it a typed object.

The most straightforward way to solve this looks a little gross and uses the JSON methods stringify and parse, back to back:

const jsonObject = JSON.parse(JSON.stringify(typedObject));

And now FireBase will happily accept your object.

When retrieving this object back from FireBase you will need to remember to reconstruct the object before passing it through to your services and UI.

When listening to a whole collection:

getAllMyCollection(): Observable {
  return this.db.collection(`MyCollection`).snapshotChanges().pipe(
    map(actions => actions.map(action => {
      const data = new MyCollectionObject(action.payload.doc.data());
      data.id = action.payload.doc.id;
      return data;
    }))
  );
}

Or if you just to listen to a single object:

getMyCollectionObject(id): Observable {
  return this.db.doc(`MyCollection/${id}`).snapshotChanges().pipe(map(action => {
      const data = action.payload.data() as any;
      const newObject = new MyCollectionObject({id: action.payload.id, ...data});
      return newObject;
    }));
  }
}