-2

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?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Richie Zakaria
  • 81
  • 1
  • 2
  • 10
  • 3
    That's happening at runtime, in _JavaScript_. Evidently your type is not an accurate reflection of the real input. – jonrsharpe May 18 '22 at 18:01
  • 2
    Main problem: [Adding two numbers concatenates them instead of calculating the sum](https://stackoverflow.com/q/14496531) While your problem is that you are *not* calling `getDir(10);` [You can see that exact code is working](https://www.typescriptlang.org/play?#code/MYewdgzgLgBA5gUygEQJYCcYF4YAoA2AhtAJJgAmCAHgFwxgCuAtgEYLoCU2AfDAN4AoAPRCYTAJ4wQUABbsYoSgNCQQ+BADp8IOAWJQylKjADUMAIwAGLiJjoEEBvlioIFy1YEBfAQMQoMXCsOAG4gA). Most likely you are calling something that amounts to `getDir(someValue as number);` – VLAZ May 18 '22 at 18:02
  • @jonrsharpe thanks for advice. when I changed the type number to any and do parseInt(lastIndex) first, the result is 20 now. – Richie Zakaria May 18 '22 at 18:08

1 Answers1

2

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)
mwilson
  • 12,295
  • 7
  • 55
  • 95