Discriminated Unions in Typescript Function Parameters for Firebase SDK Type Definitions

Hello my dear Overflowers,

Working with Firebase on the client side and in Firebase Functions requires two different sdks, the firebase-sdk on the client environment and the firebase-admin-sdk in the cloud environment. https://firebase.google.com/docs/firestore/extend-with-functions

I have shared functionality between cloud functions and the client, one is for example getting multiple collections and assembling a document out of it. This is required since on writing the document from the client a cloud function is triggered that does additional computation that might require to pull other documents.

The idea is to create a common file that can be pulled in from both sides without any additional dependencies that would pollute the cloud function build or the client build.

For that ideally I would have type unions in the following pattern:

import firebase from "firebase";
import admin from "firebase-admin";

export type FirestoreConnection = firebase.firestore.Firestore | admin.firestore.Firestore;
export type FirestoreDocumentReference = firebase.firestore.DocumentReference | admin.firestore.DocumentReference;
export type FirestoreDocumentData = firebase.firestore.DocumentData | admin.firestore.DocumentData;

This would allow me to create a function interface like this:

getDocument(firestoreConnection: FirestoreConnection, documentUid: string) : FirestoreDocumentData {
...
}

However the issue is that through the type union to my understanding both dependencies would be pulled in, the firebase-sdk as the firebase-admin-sdk.

Also to my understanding pre-processor statements are not available in typescript. This would allow me to exclude the other dependencies by removing the code for either build:

#if client {
import firebase from "firebase";
} else {
import admin from "firebase-admin";
}
#if client {
export type FirestoreConnection = firebase.firestore.Firestore
...
} else {
export type FirestoreConnection = admin.firestore.Firestore;
...
}

There seems to be a manual work around however this seems to introduce quite some complexity and also seems not to be compatible with IDEs like VSCode or WebStorm.

What would be the correct way of creating a shared function that can depend on both types but will only pull in either or?

Looking forward to ideas!



Read more here: https://stackoverflow.com/questions/66343056/discriminated-unions-in-typescript-function-parameters-for-firebase-sdk-type-def

Content Attribution

This content was originally published by Solipsus at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: