Typescript: TS 3.7: optional chaining not working in this case

Created on 19 Oct 2019  ·  2Comments  ·  Source: microsoft/TypeScript

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)

Most helpful comment

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

All 2 comments

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.

Was this page helpful?
0 / 5 - 0 ratings