benjaminz benjaminz - 7 months ago 226
TypeScript Question

TypeScript: error when using parseInt() on a number

The JavaScript function

can be used to force conversion of a given parameter to an integer, whether that parameter is a string, float number, number, etc.

In JavaScript,
would yield
with no errors, however, in TypeScript, it throws an error during compilation saying:

error TS2345: Argument of type 'number' is not assignable to parameter of type 'string'.

Am I missing something here or is it an expected behaviour from TypeScript?


Don't use parseInt to do this operation -- use Math.floor.

Using parseInt to floor a number is not always going to yield correct results. parseInt(4e21) returns 4, not 4e21. parseInt(-0) returns 0, not -0.