In Firestore, how can I prevent "Please ensure that the Firestore types you are using are from the same NPM package" errors

Viewed 239

I have several NPM codebases that use Firestore. One is client-side, one is server-side, and I am trying to refactor some code to a common dependency codebase. The server codebase uses firebase-admin as its dependency, but if I try to set objects with sentinel types (e.g. firebase.firestore.Timestamp), I incur this error:

Please ensure that the Firestore types you are using are from the same NPM package

I can avoid mixing firestore implementations by injecting the instance into my library codebase, e.g.:

import * as admin from "firebase-admin";
const libraryCode = new MyFirestoreLibrary(admin.firestore())

But, are there ways to access these sentinel types in library code?

An example of what I'm hoping to make work is here: https://github.com/okhobb/firestore-dependency-tester

1 Answers

I agree this is extremely silly from the firebase team. I'm in your exact sitiuation, and have shared code where I define types and objects between both client and server - sounds reasonable right?

Here's my workaround:


import * as firebase from 'firebase-admin';
import Timestamp = firebase.firestore.Timestamp;


export const now = () => {
  const newTimestamp = Timestamp.fromMillis(Date.now()) as any;
  const ret =  JSON.parse(JSON.stringify(newTimestamp));


  for (const prop of Object.getOwnPropertyNames(Timestamp.prototype).filter(prop => prop !== "constructor"))
    ret[prop] = newTimestamp[prop]


  return ret as Timestamp;
}

This just creates a new object and copies the properties so that the toDate, toMillis etc functions are all still there, it's just not a direct instance of timestamp, so any instanceof checks will return false.

After doing that awful hack, it seems like the check they have in place to make sure "you are importing from the same npm package" no longer works.

Related