How to fix error TS2533: "Object is possibly 'null' or 'undefined'" in TypeScript
Hello! I'm new to TypeScript and trying to write a simple function for working with an array of users. I have a User interface and a function that searches for a user by id:
```typescript
interface User {
id: number;
name: string;
email: string;
}
const users: User[] = [
{ id: 1, name: 'Alice', email: 'alice@example.com' },
{ id: 2, name: 'Bob', email: 'bob@example.com' }
];
function findUser(id: number): User {
return users.find(user => user.id === id);
}
const user = findUser(1);
console.log(user.name);
```
But the compiler gives an error:
```
error TS2533: Object is possibly 'null' or 'undefined'.
```
The error occurs on the line `console.log(user.name)`. I understand that `find` can return `undefined` if the user is not found, but I'm sure th
No answers yet.
Log in to leave an answer
Blogs