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

Number type narrowing from number|undefined within arithmetic conditions #13974

Closed
Knagis opened this issue Feb 9, 2017 · 2 comments
Closed
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug

Comments

@Knagis
Copy link
Contributor

Knagis commented Feb 9, 2017

TypeScript Version: 2.1.5

JavaScript evaluates undefined > 0 (and other similar constructs) as false and this could be used for type narrowing. Unlike comparisons with null, undefined is rather consistent (https://jsfiddle.net/4u11p7u0/1/).

Code

let a: number | undefined;

function expectNumber(a: number) { }

if (a != null) {
    // works
    expectNumber(a);    
}

if (a > 0) {
    // does not work but should because "undefined > 0 === false"
    expectNumber(a);
}

Expected behavior:

the if (a > 0) branch narrows the type to number.

Actual behavior:

the type of a within the branch stays as number|undefined.

@ahejlsberg
Copy link
Member

We're actually going in the opposite direction on this one. In the upcoming TypeScript 2.2 release, for an operand a that is possibly undefined we consider the expression a > 0 to be an error. See #13483 for more details.

Generally the results of the <, >, <=, and >= operators with null and undefined operands are surprising and merit reporting an error. For example, a > 0 and a < 0 are both false when a is undefined.

@ahejlsberg ahejlsberg added Discussion Issues which may not have code impact Working as Intended The behavior described is the intended behavior; this is not a bug and removed Discussion Issues which may not have code impact labels Feb 10, 2017
@Knagis
Copy link
Contributor Author

Knagis commented Feb 11, 2017

Thank you for the information.

@Knagis Knagis closed this as completed Feb 11, 2017
@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
Working as Intended The behavior described is the intended behavior; this is not a bug
Projects
None yet
Development

No branches or pull requests

2 participants