TypeScript Version: 3.7.x-dev.201xxxxx
Search Terms:
optional chaining
Code
function arrayHasLength(): boolean {
const someArray = [] as any[] | null;
return someArray?.length > 0;
}
Expected behavior:
It compiles.
Actual behavior:
Error: Object is possibly 'undefined'.(2532)
This works correctly. someArray?.length is possible undefined, and you can't greater-compare undefined with 0.
You can fix this by writing (someArray?.length ?? 0) > 0 (or similar).
@MartinJohns I like your proposed workaround, though all in all it does not read as nice, but I see the issue now.
Most helpful comment
This works correctly.
someArray?.lengthis possibleundefined, and you can't greater-compareundefinedwith0.You can fix this by writing
(someArray?.length ?? 0) > 0(or similar).