Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firestore Document Typescript doc.data() undefined?

Currently cleaning up a bit of code and rewritting a lot in typescript. What I found what made me curious is the following code:

    const userRef = firestore.collection('users').doc(userId);
    const userDoc = await userRef.get();

    if (userDoc.exists) {
        const userData = userDoc.data();

        const currentUserBalance = userData.balance ? userData.balance : 0;
    }

Now Typescript will complain that userData is possibily undefined, but the Documents .data() cannot be undefined when I check for the document existing above in my if block. Just curious on why that happens and if I have a logic issue here or not.

like image 385
Badgy Avatar asked Sep 06 '26 05:09

Badgy


1 Answers

TypeScript doesn't have any knowledge of the relationship between exists and data(). It just knows the signature of data() says that the return value can be DocumentSnapshot or undefined. So, you must satisfy the compiler by either:

  1. First checking for "truthiness", then use the results if so:
const data = userDoc.data()
if (data) {
    // In this block, data is now typed as just DocumentData,
    // undefined is no longer an option.
}
  1. Telling TypeScript that you know for sure that the results will be "truthy" by using the ! operator:
const data = userDoc.data()!  // data is now typed as just DocumentData
like image 84
Doug Stevenson Avatar answered Sep 07 '26 17:09

Doug Stevenson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!