TS2532 Error: Object is possibly 'undefined' in TypeScript — how to fix?
Hello everyone! I'm new to TypeScript and working on a project with Firebase Cloud Functions and Firestore. I have a function that retrieves data from a Firestore document and processes it. But TypeScript keeps throwing error TS2532: "Object is possibly 'undefined'". Here's my code:
```typescript
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
admin.initializeApp();
export const processUserData = functions.firestore
.document('users/{userId}')
.onCreate(async (snap, context) => {
const data = snap.data();
const userName = data.name; // TS2532 error here
const userAge = data.age; // And here too
console.log(`User ${userName} is ${userAge} years old.`);
});
```
I understand that `data` could be `undefined` if the document doesn't exist. But how do I handle this properly? I tried simply checking `if (data)`, but the error still appears on the lines where I access the properties. Maybe there's a more elegant way?