Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
60
rated 0 times [  65] [ 5]  / answers: 1 / hits: 58122  / 7 Years ago, wed, february 8, 2017, 12:00:00

I work with WebStorm 2016.2.2, TypeScript 2.1, Node.js.


For some reason, isNaN is declared as a function that only accepts a number:


declare function isNaN(number: number): boolean;

I tried to change it to any, but it looks like it doesn't influence on the TSC. I still get the same error:



Argument of type 'string' is not assignable to parameter of type
'number'



My code (simplified):


isNaN("10");

How can I solve/workaround it?




Edit:


Notice that according to specification, isNaN's parameter can be any type: Number.isNaN()


Also: My code was simplified. I actually receive a parameter that may be either a string or a number, and if it's a string it may be either a stringy number that I would like to convert to number ("10") or a simple string ("Hello world").


I didn't want to make this question long by including my entire code, but because it caused confusion, this is my real code:


            if (typeof expectedValue === "string" && !isNaN(expectedValue)) {
expectedValue = +expectedValue;
}

if (typeof actualValue === "string" && !isNaN(ctualValue)) {
actualValue = +actualValue;
}

switch (this.operator) {
case Operator.equal:
return actualValue == expectedValue;
case Operator.notEqual:
return actualValue === undefined || actualValue != expectedValue;
case Operator.greaterThan:
return actualValue > expectedValue;
case Operator.littleThan:
return actualValue < expectedValue;
case Operator.greaterOrEqual:
return actualValue >= expectedValue;
case Operator.littleOrEqual:
return actualValue <= expectedValue;
}

More From » node.js

 Answers
46

I advise you to implement your code differently.

The reasons:




  1. It might be short, but it's not easy to understand what's going on

  2. Using isNaN isn't the best option here: isNaN() returns false as well



You better try to convert the value into a number and check if that's NaN or not (as @smnbbrv wrote):



if (typeof expectedValue === string && !Number.isNaN(Number(expectedValue))) {
expectedValue = Number(expectedValue);
}





Edit



You can pass your value as any:



isNaN(ctualValue as any)


To bypass the compiler check.


[#59014] Tuesday, February 7, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
domeniccolti

Total Points: 276
Total Questions: 98
Total Answers: 93

Location: India
Member since Fri, May 13, 2022
2 Years ago
domeniccolti questions
Mon, Oct 18, 21, 00:00, 3 Years ago
Thu, Oct 14, 21, 00:00, 3 Years ago
Thu, Jul 15, 21, 00:00, 3 Years ago
Sat, Oct 24, 20, 00:00, 4 Years ago
Thu, Sep 3, 20, 00:00, 4 Years ago
;