I've been having a really strange Object is possibly 'undefined' error. My goal is an condition like this:
if (productPages?.length && productPages[productPages.length - 1].docs?.length < 10){...}
But the condition productPages[productPages.length - 1].docs?.length < 10 leads me the error Object is possibly 'undefined'.
The thing is If I change the < operator for another one like == or === the error disappears, which, to me, seems odd.
I don't want to use the ! - Non-null assertion operator, but I can't find any other solution for it.
Typescript versions tested: 3.7.3 and 4.0.5.
The whole left side will evaluate to undefined if the optional chaining falls through. In such a case, your code is like:
if (undefined < 10)
Which doesn't make sense, so TypeScript raises the error.
Using === isn't a problem because checking to see if a value is === to undefined is not nonsensical.
If the docs will definitely exist, then remove the optional chain from it: .docs.length. But since you don't know whether the productPages[productPages.length - 1] exists, you'll need an optional chain for it as well. (Your ?. might be in the wrong place.)
If you don't know if the docs will exist or not, you'll need to figure out the logic you want: do you want to run the code if the nested array isn't found, or do you want to run the code only if the nested array is found? Change to something like:
const length = productPages[productPages.length - 1]?.docs?.length;
if (length !== undefined && length < 10) {
// or
// if (length === undefined || length < 10) {
depending on the logic you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With