Skip to content

Element access with non-literal constant key should be narrowable #36230

Closed
@thany

Description

@thany

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'

Playground Link

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions