Skip to content

strictNullChecks thinks a value may be null if null is assigned to it in its non-null branch #7630

Closed

Description

@Arnavion

TypeScript Version:

3853bb8 (master after merging #7140 )

Code

class Prop {
    value: any;
}

var x: Prop | null = null;
if (x === null) {
    ;
}
else if (x.value === null) { // Line 9
    x = null;
}

tsc -t es5 --strictNullChecks ./foo.ts

Expected behavior:

Compiles.

Actual behavior:

foo.ts(9,10): error TS2531: Object is possibly 'null' or 'undefined'.


If the x = null; assignment (line 10) is removed, it does compile, and x is correctly inferred to be non-null in the condition and body of the else-if block. But this assignment should not have any effect on the nullability of x in the else-if condition.

Activity

  1. weswigham commented on Mar 22, 2016

    @weswigham
    Member

    Im pretty sure the reason is this: Assignment within a block disabled narrowing within it. If so, the solution is likely already in the works: Control flow based type guards (See PR #6959)

  2. Arnavion commented on Mar 22, 2016

    @Arnavion
    Author

    Disabling narrowing within the block is one thing, but line 9 is before the block.

  3. RyanCavanaugh commented on Mar 22, 2016

    @RyanCavanaugh
    Member

    Assignments anywhere within the scope of a variable disable type guards (for now).

    As you've noticed, this makes null checks extremely cumbersome, which is why control flow analysis was bumped up in priority.

  4. locked and limited conversation to collaborators on Jun 19, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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