Skip to content

Nested optional property existence check via Boolean() cause false possibly undefined error #11088

Closed
@zfeher

Description

@zfeher

TypeScript Version: 2.0.3

Code
Nested optional property existence check via !! vs. Boolean()

// strictNullChecks: true

interface Address {
  country: string;
}

interface Student {
  address?: Address;
}

const student: Student = {
  address: {
    country: 'US',
  }
};

// this one works just fine, no error reported
const b1: boolean = student && !!student.address && student.address.country === 'US';

// this one reports an error for the second student.address: Object is possibly 'undefined' 
// whereas !!something should be the same as Boolean(something)
const b2: boolean = student && Boolean(student.address) && student.address.country === 'US';

Expected behavior:
"Object is possibly 'undefined' error" should not be reported when accessing student.address after the existence of address on student is verified.

Actual behavior:
"Object is possibly 'undefined' error" is reported when student.address is accessed the second time after its existence is already verified.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions