Closed
Description
TypeScript Version: 3.7.4 (also tried vNightly on the playground)
Search Terms: exhaustive type check array
Code
Error ts2532:
type Progress = Array<number | undefined> | undefined;
const progress: Progress = [1, 2, 3];
const index = 1;
if (progress !== undefined && progress[index] !== undefined && progress[index] >= 0) {
// Do something
}
Workaround, but undesirable:
type Progress = Array<number | undefined> | undefined;
const progress: Progress = [1, 2, 3];
const index = 1;
if (progress !== undefined)
const p = progress[index];
if (p !== undefined && p >= 0) {
// Do something
}
}
Expected behavior:
The exhaustive type checking mechanism in Typescript should know that neither progress
nor progress[index]
are undefined inside the if statement, because I'm doing an explicit check for that.
Actual behavior:
On progress[index] >= 0
you'll get ts2532: Object is possibly 'undefined'
Related Issues:
In #34661 the workaround seemed to be to use an intermediate variable, which will fix my code as well, while also making it more hairy.