When working with TypeScript, specifying a type
does not automatically handle the conversion for you; you need to take care of that process yourself.
In this specific scenario, it's important to note that the argument being passed to the getDir
function is a string rather than a number.
The code snippet provided in the answer successfully achieves the desired outcome (resulting in 20
). You can experiment with it further by visiting this link
If the conversion is not managed properly, concatenation instead of addition will occur when using string + string
in JavaScript.
There are various methods to convert strings into numbers in JavaScript. One simple approach involves preceding your number with a +
, like so: +'10' + 10
For example:
console.log('Should be 20: ', 10 + 10)
console.log('Should be 1010: ', '10' + 10)
console.log('Should be 20: ', +'10' + 10)