修复 TypeScript 类型错误
用户遇到了一个棘手的 TypeScript 类型错误,Agent 分析代码并找出根本原因。
这个函数报错了:
interface User {
id: number;
name: string;
email?: string;
}
function processUsers(users: User[]): string[] {
return users.map(user => user.email.toUpperCase());
// ❌ Error: Object is possibly 'undefined'.
}
问题是 email 字段是可选的(email?: string),可能为 undefined。需要过滤掉没有 email 的用户。
过滤掉 undefined 并确保类型安全:
function processUsers(users: User[]): string[] {
return users
.filter((user): user is User & { email: string } =>
user.email !== undefined
)
.map(user => user.email.toUpperCase());
}
✅ 修复完成。使用了类型守卫(Type Guard)确保类型安全。
💡 要点
- Agent 理解 TypeScript 类型系统
- 使用类型守卫解决可选字段问题
- 提供类型安全的解决方案