【问题标题】:TS2531: Object is possibly 'null'. Ionic - Vue.jsTS2531:对象可能为“空”。离子 - Vue.js
【发布时间】:2021-08-27 20:55:13
【问题描述】:

我目前正在与错误作斗争:

TS2531: Object is possibly 'null'.

它是基于这个逻辑出现的:

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

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

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

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

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

我正在使用 Ionic 4 和 Vue.js。

提前致谢!

【问题讨论】:

  • 你能显示this.Listen 被分配到的代码吗?
  • 试试可选链aNewList = this.Listen?.filter
  • @BoussadjraBrahim 在这种情况下,| undefined 将传播到 aNewList。
  • @CertainPerformance 列表由 setup() 函数返回。它的定义如下: const = ref(null); - 包含对象数组
  • 请把所有相关代码放入问题中。

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


【解决方案1】:

如前所述,它会通知您Listen 可能为空,因此您的代码可能正在尝试运行 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 () {}

【讨论】:

    【解决方案2】:

    可能是null 的变量和属性自然会通过类型保护来处理:

    如果 (this.Listen) { // null 从 Listen 类型中排除 }

    否则可以使用非空断言:

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

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

    ...
    Listen: null!,
    ...
    

    【讨论】:

      猜你喜欢
      • 2021-02-14
      • 1970-01-01
      • 1970-01-01
      • 2021-07-11
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 2019-11-23
      相关资源
      最近更新 更多