Skip to content

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

Description

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.

Activity

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

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions