Thijs Koerselman
Thijs Koerselman

Reputation: 23271

How to get type inference from Firestore DocumentSnapshot exists

The following is a pretty common scenario for me:

type SomeDocument = {
  foo: string;
};

export async function getSomeDocument(): Promise<SomeDocument> {
  const doc = await db
    .collection("some")
    .doc("document")
    .get();

  if (!doc.exists) throw new Error("Missing some document");

  return doc.data();
}

Typescript doesn't allow this because the doc.data() return type is DocumentSnapshot | undefined. Somehow I feel that Typescript should be able to know that doc.data() is going to return a DocumentSnapshot because of the doc.exists check that preceded it.

Would this be possible using correct type annotation in the current version of Typescript?

I currently solve this by casting the return statement with as SomeDocument

Upvotes: 0

Views: 711

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317412

You've already identified exactly what you're supposed to do - return doc.data() as SomeDocument. TypeScript isn't going to allow one thing to simply become another thing that's not naturally part of its inheritance or implemented interfaces. You have to be explicit about casting the type in this case. Accessing the exists property doesn't change the situation, from the perspective of TypeScript.

Upvotes: 2

Related Questions