Introduction: Why a Simple Task Breaks Code
\n\nEvery developer working with TypeScript eventually faces the task: "How to convert a string to a number?". It seems like it couldn't be simpler. But this seemingly trivial operation becomes the source of dozens of bugs, especially at the intersection of frontend and backend, where data comes from input forms, APIs, or CSV parsing.
\n\nOn Stack Overflow, the question "How to convert a string to number in TypeScript?" has garnered tens of thousands of views. And this is no coincidence. Developers get lost in the nuances: NaN, parseInt vs Number(), loss of precision, and unexpected behavior with empty strings. In this article, we will analyze the top errors when converting a string to a number in TypeScript and show how to avoid them. You will learn which method to choose for a specific task and how to write truly reliable code.
Main Ways to Convert a String to a Number in TypeScript
\n\nBefore discussing errors, let's recall the tools available in a TypeScript developer's arsenal. Each behaves differently, and choosing the wrong method is the first and main mistake.
\n\n1. The Number() Function
\nThe most obvious way. Number(value) attempts to convert the passed value to a number. If this is impossible, it returns NaN.
const str: string = "42";\nconst num: number = Number(str);\nconsole.log(num); // 42\n\nconst invalid: string = "hello";\nconst badNum: number = Number(invalid);\nconsole.log(badNum); // NaN\n\n2. Unary Plus (+)
\nA short syntax that does the same thing as Number(). It's concise but can be confusing for beginners.
const price: string = "99.99";\nconst numericPrice: number = +price;\nconsole.log(numericPrice); // 99.99\n\nconst empty: string = "";\nconst zero: number = +empty;\nconsole.log(zero); // 0 — caution, this is a common pitfall!\n\n3. parseInt() and parseFloat()
\nSpecialized functions for parsing integers and floating-point numbers. They "extract" the numeric part from the string, ignoring subsequent characters.
\n\nconst userInput: string = "123px";\nconst width: number = parseInt(userInput, 10);\nconsole.log(width); // 123 — the 'px' characters are discarded\n\nconst height: string = "45.67em";\nconst parsedHeight: number = parseFloat(height);\nconsole.log(parsedHeight); // 45.67\n\n4. Bitwise Operators (~~, | 0)
\nAn exotic method that came from JavaScript. It only works for integers and discards the fractional part.
\n\nconst str: string = "7.8";\nconst result: number = ~~str;\nconsole.log(result); // 7 — fractional part is lost\n\nTop 5 Errors When Converting a String to a Number in TypeScript
\n\nNow that we've covered the tools, let's look at where developers most often stumble. These errors are real "rakes" that even experienced programmers step on.
\n\nError #1: Ignoring NaN
\nThe most common mistake is not checking the result for NaN. TypeScript will not throw an error if you use NaN in arithmetic operations or comparisons, but the result will be unexpected.
const input: string = "not a number";\nconst value: number = Number(input);\n\n// Error: NaN participates in calculations\nconst total = value + 10;\nconsole.log(total); // NaN\n\n// Comparison with NaN is always false\nif (value === NaN) {\n console.log("This will never work");\n}\n\nHow to avoid: Always use isNaN() or Number.isNaN() for checking. The second option is preferable as it does not coerce non-numeric types.
if (Number.isNaN(value)) {\n console.error("Not a number entered");\n // You can return a default value or show an error