当使用 Array.find() 方法时,需要注意返回值类型为可选值(optional),因为在数组中可能找不到指定的元素,此时返回值为 undefined。因此,应该使用可选值运算符(Optional Chaining Operator)来避免出现类型错误。
示例代码:
interface Person {
name: string;
age: number;
}
const people: Person[] = [
{ name: 'Alice', age: 30 },
{ name: 'Bob', age: 25 },
{ name: 'Charlie', age: 40 }
];
const alice: Person | undefined = people.find(person => person.name === 'Alice');
console.log(alice?.age); // 输出:30
在上面的示例代码中,使用了可选值运算符 (?.) 来解决类型错误。如果找到了目标元素,那么返回目标元素的年龄;否则返回 undefined。