Skip to content

Property cannot be accessed on possibly null value even when protected by if statement #5479

@kumar303

Description

@kumar303

Reproducible in the latest version (0.60.1): Try Flow

Consider these types:

type Prefs = {
  favorite_color: string,
  favorite_number: string,
};

type Person = {
  prefs: Prefs | null,
};

const person: Person = { prefs: null };

Given these types, Flow does not understand that subsequent lines are still protected by an if statement. It only understands that the first line is protected. Example:

if (person.prefs) {
  // This does not cause an error.
  console.log(person.prefs.favorite_color);
  // This causes an error (but should not).
  console.log(person.prefs.favorite_number);
}

Flow reports this error which is incorrect since the code is protected by an if statement:

17:   console.log(person.prefs.favorite_number);
                               ^ property `favorite_number`. Property cannot be accessed on possibly null value
17:   console.log(person.prefs.favorite_number);
                  ^ null

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions