TS2531:对象可能为“空”。离子 - Vue.js

时间:2021-06-10 20:32:42

标签: typescript vue.js ionic-framework error-handling ionic4

我目前正在努力解决错误:

TS2531: Object is possibly 'null'.

它是基于这个逻辑产生的:

let aNewList = [];
aNewList = this.Listen.filter( function(item) { return item !== ID });

Listen 由 setup() 函数返回。它的定义如下:

const = ref(null); - 包含对象数组

我确信this.Listen 已经填满了。 但是在使用 .filter 等函数时,错误不会让我启动我的应用程序。

有谁知道我如何抑制这个错误?

我在 Vue.js 中使用 Ionic 4。

提前致谢!

2 个答案:

答案 0 :(得分:1)

正如已经提到的,它会通知您 Listen 可能为 null,因此您的代码可能会尝试运行 undefined.filter() 这将无法正常工作。

问题仍然存在,您希望发生什么,我假设答案是返回一个空数组,因此您可以执行以下任一操作:

// use optional chaining and return [] instead of undefined
let aNewList = this.Listen?.filter( function(item) { return item !== ID }) || [];

// filter on empty array
let aNewList = (this.Listen || []).filter( function(item) { return item !== ID });


// handle in try..catch but this might not suppress the actual eslint notice, but would handle the exception even when optional chaining is not available.
let aNewList = []
try(){
  aNewList = this.Listen.filter( function(item) { return item !== ID });
} catch () {}

答案 1 :(得分:0)

可能是 null 的变量和属性自然会使用类型保护措施进行处理:

if (this.Listen) { // 从监听类型中排除 null }

否则可以使用非空断言:

aNewList = this.Listen!.filter(...);

如果一个值在不久之后被初始化并保证在所有使用它的地方不为空或未定义,则可以对变量或属性声明进行非空断言:

...
Listen: null!,
...