How can I solve the error 'TS2532: Object is possibly 'undefined'?

后端 未结 2 2043
小蘑菇
小蘑菇 2020-12-01 13:30

I\'m trying to rebuild a web app example that uses Firebase Cloud Functions and Firestore. When deploying a function I get the following error:

src/index.ts         


        
2条回答
  •  有刺的猬
    2020-12-01 14:08

    Edit / Update:

    If you are using Typescript 3.7 or newer you can now also do:

        const data = change?.after?.data();
    
        if(!data) {
          console.error('No data here!');
           return null
        }
    
        const maxLen = 100;
        const msgLen = data.messages.length;
        const charLen = JSON.stringify(data).length;
    
        const batch = db.batch();
    
        if (charLen >= 10000 || msgLen >= maxLen) {
    
          // Always delete at least 1 message
          const deleteCount = msgLen - maxLen <= 0 ? 1 : msgLen - maxLen
          data.messages.splice(0, deleteCount);
    
          const ref = db.collection("chats").doc(change.after.id);
    
          batch.set(ref, data, { merge: true });
    
          return batch.commit();
        } else {
          return null;
        }
    

    Original Response

    Typescript is saying that change or data is possibly undefined (depending on what onUpdate returns).

    So you should wrap it in a null/undefined check:

    if(change && change.after && change.after.data){
        const data = change.after.data();
    
        const maxLen = 100;
        const msgLen = data.messages.length;
        const charLen = JSON.stringify(data).length;
    
        const batch = db.batch();
    
        if (charLen >= 10000 || msgLen >= maxLen) {
    
          // Always delete at least 1 message
          const deleteCount = msgLen - maxLen <= 0 ? 1 : msgLen - maxLen
          data.messages.splice(0, deleteCount);
    
          const ref = db.collection("chats").doc(change.after.id);
    
          batch.set(ref, data, { merge: true });
    
          return batch.commit();
        } else {
          return null;
        }
    }
    

    If you are 100% sure that your object is always defined then you can put this:

    const data = change.after!.data();
    

提交回复
热议问题