Home > Back-end >  Firestore withConverter returns QueryDocumentSnapshot instead of Class in TS
Firestore withConverter returns QueryDocumentSnapshot instead of Class in TS

Time:12-15

I'm trying to use the withConverted method of Firestore to returns queries as my custom class in Typescript.

EventConverter Class

import Event from "@/models/Event";

class EventConverter implements FirestoreDataConverter<Event> {
    toFirestore(event: PartialWithFieldValue<Event>): DocumentData {
        return {
            id: event.id,
            code: event.code
        }
    }

    fromFirestore(snapshot: QueryDocumentSnapshot): Event {
        const data = snapshot.data()
        return new Event(
            data.id,
            data.code
        )
    }
}

export default EventConverter

Calling code As you can see the return type I expect is an Event, such as I define in my eventConverter

export async function getEventFromCode(code: string): Promise<Event> {
    const q = query(
        collection(db, 'events').withConverter(new EventConverter()),
        where('code', '==', code),
        limit(1)
    )

    const querySnapshot = await getDocs(q)
    return querySnapshot.docs[0]
}

However Typescript is letting me know:

TS2740: Type 'QueryDocumentSnapshot ' is missing the following properties from type 'Event': bubbles, cancelBubble, cancelable, composed,

CodePudding user response:

It might seem that you are casting to this event:

https://developer.mozilla.org/en-US/docs/Web/API/Event

Instead of your custom class called Event.

  • Related