How to convert a string to a number in TypeScript (and JavaScript)?
Hello everyone! I just started learning TypeScript, and I have a problem with converting strings to numbers. In regular JavaScript, I used `parseInt()` or `Number()`, but in TypeScript, everything works a bit differently due to strict typing.
Here's an example of my code:
```javascript
const userInput: string = "42";
const age: number = parseInt(userInput); // error!
```
TypeScript throws an error that `parseInt` returns `number`, but I want to assign this value to a variable with type `number`. Although it seems logical...
I also tried this:
```javascript
const price: string = "19.99";
const total: number = Number(price);
```
But TypeScript complains that `Number` can return `NaN`, and `NaN` has type `number`, but it's not really a number. I'm confused.
Tell me, how to properly
No answers yet.
Log in to leave an answer
Blogs
How to Write a REST API in TypeScript in 30 Minutes