Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is addition in TypeScript weird?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading