Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
Arnavion opened this issue Mar 22, 2016 · 3 comments
Labels
Duplicate An existing issue was already created

Comments

@Arnavion
Copy link
Contributor

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.

@weswigham
Copy link
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)

@Arnavion
Copy link
Contributor Author

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

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Mar 22, 2016
@RyanCavanaugh
Copy link
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.

@microsoft microsoft locked and limited conversation to collaborators Jun 19, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

3 participants