[英]Object is possibly null error Typescript when doing comparison
I have a simple sort:我有一个简单的排序:
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;
});
The "Data" type is: “数据”类型是:
export type Data = {
[key: string]: string | number | null;
};
I check if a[label] and b[label] are both null and I still get the error "Object is possibly 'null'.ts(2531)".我检查 a[label] 和 b[label] 是否都是 null 并且我仍然收到错误“对象可能是 'null'.ts(2531)”。 It seems to only happen with the > and < operators.
它似乎只发生在 > 和 < 运算符上。
It's probably just not smart enough to see that you checked.可能只是不够聪明,无法看到您检查过。 BTW you didn't post where
label
was coming from, but assuming that's not the problem, try this:顺便说一句,您没有发布
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;
});
Sometimes you have to factor things out so that TypeScript can see that you've checked for conditions like === null
.有时您必须考虑因素,以便 TypeScript 可以看到您已经检查了诸如
=== null
类的条件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.