Skip to content

Improve typing of && operator with --strictNullChecks #8949

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

Merged
merged 2 commits into from
Jun 8, 2016

Conversation

ahejlsberg
Copy link
Member

This PR improves the types produced by the && operator in strict null checking mode. Given operands a and b of types A and B, the operation a && b produces a value of type A' | B where A' is the type formed by removing all but the possibly-falsy types from A. The possibly-falsy types are string, number, boolean, void, undefined, and null. This change in particular accounts for the situations where the left operand is "", 0, or false which previously weren't reflected in the resulting types.

Some examples:

function f1(s: string | undefined) {
    let x = s && s.length;  // string | number | undefined
}

function f2(o: { n: number } | null) {
    let x = o && o.n;  // number | null
}

Fixes #8892.

@ahejlsberg ahejlsberg changed the title Improve typing of && operator with --strictNullChecks Improve typing of && operator with --strictNullChecks Jun 3, 2016
@ivogabe
Copy link
Contributor

ivogabe commented Jun 4, 2016

Could x be inferred to "" | number | undefined? That would be more accurate and that would also allow this, if "" would be taken into account by || too:

function f3(s: string | undefined) {
   let x = s && s.length || 0; // number
}

@mhegazy
Copy link
Contributor

mhegazy commented Jun 8, 2016

👍

@ahejlsberg ahejlsberg merged commit aeb1d97 into master Jun 8, 2016
@ahejlsberg ahejlsberg deleted the strictNullLogicalAnd branch June 8, 2016 23:27
@GoToLoop
Copy link

GoToLoop commented Jun 13, 2016

This PR has broken && || expressions for good under strict mode! :..(

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants