1

I am using the Firebase JavaScript Version 9 SDK.

And I'm trying to use withConverter() to cast data coming to and from Firestore with TypeScript interfaces.

There is an article here that explains how to do it using a generic converter. It allows you to create one generic converter and re-use that instead of creating new converter logic for each Interface. Here is a GIST with all the code from the article and comments explaining it well.

And here is my attempt at implementing that generic converter:

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
);

But I am getting this TypeScript error on converter<User>() saying this:

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)

Why am I getting this error?

1 Answer 1

1

Figured it out.

When looking at this help doc I found the correct converter types for Version 9 SDK were PartialWithFieldValue and QueryDocumentSnapshot.

Here is the full correct code:

interface User {
  id?: string;
  name: string;
}

const converter = <T>() => ({
  toFirestore: (data: PartialWithFieldValue<T>) => data,
  fromFirestore: (snap: QueryDocumentSnapshot) => snap.data() as T,
});

const userDocRef = doc(db, 'users', 'my-user-id').withConverter(
  converter<User>()
);

Now userDocRef has a type of DocumentReference<User>.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.