简体   繁体   中英

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)". 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:

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM