I have been exploring the capabilities of the Firebase JavaScript Version 9 SDK.
One feature that caught my attention is the withConverter(), which allows for seamless data casting between Firestore and TypeScript interfaces.
An informative article can be found here, detailing how to use a generic converter to streamline the process. The author demonstrates creating a single generic converter for reusability, eliminating the need for separate converter logic for each interface. For those interested, a GIST with code snippets and detailed explanations is available.
In attempting to implement a similar generic converter, specifically tailored towards a User interface, I encountered a roadblock:
interface User {
id?: string;
name: string;
}
const converter = <T>() => ({
toFirestore: (data: Partial<T>) => data,
fromFirestore: (snap: FirebaseFirestore.QueryDocumentSnapshot) =>
snap.data() as T,
});
const userDocRef = doc(db, 'users', 'my-user-id').withConverter(
converter<User>() // <-- Error here
);
The TypeScript error message displayed upon invoking converter<User>()
reads as follows:
No overload matches this call.
Overload 1 of 2, '(converter: null): DocumentReference<DocumentData>', gave the following error.
Overload 2 of 2, '(converter: FirestoreDataConverter<User>): DocumentReference<User>', gave the following error. ts(2769)
If anyone has insights into why this error occurs, your input would be greatly appreciated.