'Why is addition in TypeScript weird? [closed]
I don't know why the addition using parameter in TypeScript is weird.
const getDir = (lastIndex: number) => {
// my other code
console.log(lastIndex + 10) // result is 1010
}
getDir(10);
The result is showing 1010 instead 20.
Anyone have an idea what I do wrong?
Solution 1:[1]
Specifying a type in TypeScript does not handle the conversion. You have to do that yourself.
In your example, the argument being passed to your getDir function is a string and not a number.
The exact code you have posted in your answer does what you want it to (produces 20). You can check that out here
If you don't handle the conversion, string + string in javascript will be a concatenation and not an addition.
There are multiple ways to convert strings to number in JavaScript. The most simple way is to throw a + in front of your number. (+'10' + 10)
Example:
console.log('Should be 20: ', 10 + 10)
console.log('Should be 1010: ', '10' + 10)
console.log('Should be 20: ', +'10' + 10)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mwilson |
