javascript - | b[label] === null) return 0; if (direction === desc) return a[label] b[label] ? 1 : -1; return ...
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)