在本教程中,我们将学习如何解决TypeScript中Array.find()对象可能被定义的错误。
Array.find() 对象可能未定义的错误发生,如果我们没有为对象属性提供任何回退值,或者没有从find()方法返回任何东西,它将在控制台显示以下错误。
例子。
const arr = [
{ a: 1, name: "Raju" },
{ b: 2, name: "John" },
];
const result = arr.find((el) => {
return el.a === 1;
});
result.name.toLowerCase();
输出。
Object is possibly 'undefined'.
在上面的代码中,我们正在访问result.name 属性,该属性在运行arr.find() 方法之前是不可用的,所以如果name 属性在对象中不可用(例如:后台数据不可用),我们应该提供一些默认值来处理它。
为了解决这个错误,我们可以使用TypeScript中的可选链式(?)操作符。
这里有一个例子。
const arr = [
{ a: 1, name: "Raju" },
{ b: 2, name: "John" },
];
const result = arr.find((el) => {
return el.a === 1;
});
result?.name.toLowerCase();
在上面的例子中,我们使用了可选的链式运算符? 。所以它在访问result.name 之前隐含地检查result 是否为空或未定义,如果result 为空或未定义,表达式就会短路并返回undefined 。
另外,我们可以使用TypeScript中的if 条件检查来解决这个错误。
const arr = [
{ a: 1, name: "Raju" },
{ b: 2, name: "John" },
];
const result = arr.find((el) => {
return el.a === 1;
});
if (result != undefined){
console.log(result.name.toLowerCase()); // "raju"
}