[英]Object is possibly null error Typescript when doing comparison
我有一個簡單的排序:
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)”。 它似乎只發生在 > 和 < 運算符上。
可能只是不夠聰明,無法看到您檢查過。 順便說一句,您沒有發布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
類的條件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.