How can I solve the error 'TS2532: Object is possibly 'undefined'? : <p>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: </p>

<pre><code>src/index.ts:45:18 - error TS2532: Object is possibly 'undefined'.
45     const data = change.after.data();
</code></pre>

<p>This is the function:</p>

<pre><code>export const archiveChat = functions.firestore
  .document("chats/{chatId}")
  .onUpdate(change =&gt; {
    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 &gt;= 10000 || msgLen &gt;= maxLen) {

      // Always delete at least 1 message
      const deleteCount = msgLen - maxLen &lt;= 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;
    }
  });
</code></pre>

<p>I'm just trying to deploy the function to test it. And already searched the web for similar problems, but couldn't find any other posts that match my problem. </p>
