Search code examples
typescriptfirebasegoogle-cloud-firestore

Shared DocumentReference type between Firebase Admin SDK and client side Firebase JavaScript SDK


Prior to the modular firebase v9 release, DocumentReference from the firebase and firebase-admin packages were compatible. This is no the longer the case, which means my shared models now cause type errors when I try to use them in both the client side and node.js admin environments. Example:

import type { DocumentReference } from "firebase/firestore";

type Profile = {
  name: string;
  ref: DocumentReference;
}

If DocumentReference is from the client side sdk, when I try to create a Profile model in server side admin environment, which uses admin.firestore.DocumentReference, I'll get an error like:

Type 'DocumentReference<DocumentData, DocumentData>' is missing the following properties from type 'DocumentReference<DocumentData, DocumentData>': converter, type

I've been getting by with type assertions and @ts-expect-error annotations, but this is very unfortunate and gross.

Any ideas?


Solution

  • There is no easy exit here.

    Create your own DocumentReference abstraction or wrapper type and use it instead. You will still have to do the "unfortunate and gross" stuff inside that abstraction, and it will be unavoidable - you can't safely make two incompatible type compatible with each other without whatever it is you're referring to. But at least it will be limited to that one place.

    You will likely also have to make abstractions for other types that use DocumentReference, such as CollectionReference. And, possibly other types as well. By that point, you are essentially implementing adapter patterns for everything whose interface you want to unify.

    You should also expect that your abstractions might break in the future, as there is nothing guaranteeing that the different DocumentReference types from each SDK types will continue to stay the same.