Skip to content

isNaN is restricted to number as arguments only #34609

@bpazo

Description

@bpazo

TypeScript Version: 3.3.3333

Search Terms: isNaN

Code

// A *self-contained* demonstration of the problem follows...
// Test this by running `tsc` on the command-line, rather than through another build tool such as Gulp, Webpack, etc.

let someUnionType:string|number = "42";
if(isNaN(someUnionType)){
  // ..do something here if true
}else{
  // ..do something else if false
}

Expected behavior:
I expect isNaN to test a value to determine if it is NaN or not NaN, and return a boolean value accordingly.

I don't feel as though I should have to convert the union value to a number first and then test the result of that value, since isNaN will do the same without the added step. Converting a value to NaN or number using Number(x) then requires passing the result to isNaN(Number(x)) to get a true or false result.

According to some examples found at isNaN() - JavaScript | MDN, isNaN seems to handle such tests appropriately without first converting to number first.

Also, the polyfill for isNaN is:

credit: MDN isNaN polyfill

var isNaN = function(value) {
    var n = Number(value);
    return n !== n;
};

Since Number is permitted to take a value of type any, then it would seems as though isNaN should be permitted to do the same since it is basically just a different way to use Number. Also, I feel like it just breaks how isNaN was intended to be used. See this - "Confusing_special-case_behavior" for more details.

One last note, please see Useful special-case behavior for one final reason why isNaN should accept the same type parameters as Number.

Actual behavior:
Typescript errors out at before test if argument isn't of type number.
TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.

Playground Link:
Playground Link
Related Issues:

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