【问题标题】:Object is possibly null error Typescript when doing comparison进行比较时,对象可能为空错误打字稿
【发布时间】:2020-05-20 01:04:58
【问题描述】:

我有一个简单的排序:

dataCopy.sort((a: Data, b: Data) => {
  if (a[label] === null || b[label] === null) return 0;
  if (direction === "desc")
    return a[label] > b[label] ? 1 : -1;
  return 0;
});

“数据”类型是:

export type Data = {
  [key: string]: string | number | null;
};

我检查 a[label] 和 b[label] 是否都为 null,但仍然收到错误消息“对象可能为 'null'.ts(2531)”。它似乎只发生在 > 和

【问题讨论】:

    标签: javascript typescript


    【解决方案1】:

    它可能不够聪明,无法看到您检查过。顺便说一句,您没有发布 label 的来源,但假设这不是问题,试试这个:

    dataCopy.sort((a: Data, b: Data) => {
      const aLabel = a[label];
      const bLabel = b[label];
      if (aLabel === null || bLabel === null) return 0;
      if (direction === "desc")
        return aLabel > bLabel ? 1 : -1;
      return 0;
    });
    

    有时您必须排除一些因素,以便 TypeScript 可以看到您已经检查了 === null 之类的条件。

    【讨论】:

    • 谢谢,值得学习的一课。它可以判断我是否检查了变量 aLabel,但不能判断我是否检查了 a[label]。
    猜你喜欢
    • 2020-11-07
    • 1970-01-01
    • 2023-01-10
    • 2019-09-04
    • 2022-01-08
    • 2023-01-20
    • 2017-10-12
    • 2019-05-12
    • 1970-01-01
    相关资源
    最近更新 更多