Avatar ·

如何修复 TypeScript 中的 TS2533 错误:“Object is possibly 'null' or 'undefined'”

你好!我是 TypeScript 新手,正在尝试编写一个简单的函数来处理用户数组。我有一个 User 接口和一个按 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); ``` 但编译器报错: ``` error TS2533: Object is possibly 'null' or 'undefined'. ``` 错误出现在 `console.log(user.name)` 这一行。我知道如果找不到用户,`find` 可能返回 `undefined`,但我确信 id=1 的用户存在。如何正确告诉 TypeScript 该对象绝对不是 `null` 或 `undefined`?能否禁用这个检查?还是需要修改代码?感谢!