Firebase Typescript Typings not working after V8.0.0

Viewed 359

I'm facing a very similar problem as this Github issue and I can't understand how can I fix it and why the types are being exported as const from firebase sdk.

The code that reexports firebase types is the following:

import * as firebase from '@firebase/rules-unit-testing'

export type Firestore = firebase.firestore.Firestore;
export type FirestoreDocReference = firebase.firestore.Firestore;

I just want to re-export firestore types so I can declare my functions signature with typed return:

function getFirestore(auth?: any): Firestore

Reading the SDK source code I notice that firestore is being exported as follows:

declare const firestore: typeof firebase.firestore, database: typeof firebase.database;
export { firestore, database };

It is exported as a const, not a type. How can I workaround this? And why they are using const instead of type here?

1 Answers

When using declare const firestore: typeof firebase.firestore, they've essentially declared that firestore is an object, with the shape of firebase.firestore, not a namespace of types. If I recall correctly, exporting these namespace-objects was done this way so package crawlers like Webpack could correctly identify which modules needed to be bundled.

To prevent confusion, instead of importing @firebase/rules-unit-testing as firebase (which should be considered reserved), import it instead as rulesUnitTesting or similar.

import * as rulesUnitTesting from '@firebase/rules-unit-testing';

You may still use the firestore property of this to create instances of firebase.firestore.Firestore, however the types will not be available from this property.

If you wish to export the type Firestore, you would either export it from the globally defined firebase module, or explicitly import it and export from there.

import * as rulesUnitTesting from '@firebase/rules-unit-testing';
// firebase is now declared & loaded in the global types.
export type Firestore = firebase.default.firestore.Firestore;

or

import * as rulesUnitTesting from '@firebase/rules-unit-testing';
import firebase from 'firebase/app';
export type Firestore = firebase.firestore.Firestore;

or the not recommended

import * as firebase from '@firebase/rules-unit-testing';
import firebaseNamespace from 'firebase/app';
export type Firestore = firebaseNamespace.firestore.Firestore;
Related