What is the best way to define the interface of a document in firestore?

Viewed 97

I am currently wrapping my firebase calls in a function so that I can define the return type in the function, thus defining the type of a document however you have to turn the firebase call into unknown then into the interface you want otherwise typescript complains. Is there a better way to do this?

Example:

async function getAllPartials() {
    const partialDocs = await db.collection('partials').get();
    return partialDocs.docs.map(d => d.data()) as unknown as Array<Partial>
}

I also tried:

async function getAllPartials() {
    const partialDocs = await db.collection<Partial>('partials').get();
    return partialDocs.docs.map(d => d.data())
}

This says: Expected 0 type arguments but got 1;

1 Answers

I received the answer I was looking for from another platform, If anyone else is struggling with the same problem here is what we came up with:

async function getCollection<T>(name: string): Promise<Array<T>> {
  const partialDocs = await db.collection(name).get();
  return partialDocs.docs.map(d => d.data() as T);
}

T is a generic type and defines the shape of the objects in the collection. The function can now be called as:

const partials = await getCollection<Partial>('partials')

You would think that google would allow people to make it more concise by passing the argument straight to the collection like so:

db.collection<Partial>('partial')

That however does not work.

Related