9阅网

您现在的位置是:首页 > 知识 > 正文

知识

javascript - | b[label] === null) return 0; if (direction === desc) return a[label] b[label] ? 1 : -1; return ...

admin2022-11-07知识15
It's probably just not smart enough to see that you checked. BTW you didn't post where

was coming from, but assuming that's not the problem, try this:

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;
});

Sometimes you have to factor things out so that TypeScript can see that you've checked for conditions like

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

.



【回答】:

我检查a[label]和b[label]是否都是空的 但我还是得到 "Object is possibly 'null'.ts(2531) "的错误信息。这似乎只发生在>和<运算符上。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;
});

=== null我有一个简单的排序:DataCopy.sort((a: Data, b: Data) => { if (a[label] === null)