如何解决TypeScript中的Object is possibly defined错误

139 阅读1分钟

在本教程中,我们将学习如何解决TypeScript中的Object is possibly defined错误。

如果我们不为TypeScript中的对象属性提供任何回退值,它将在控制台中显示以下编译时错误。

例子。

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"
}